from datetime import datetime, timedelta
import base64, shutil, json, re, os, xlrd2 as xlrd, uuid, urllib.parse
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from Oa_system.models import official_serial_number, post_single, Staffing
from logistics.MessagePushOperationRecords import RecordAndPush
from Oa_system.models import application
import json, re, os, time
from administrative.models import *
from announcements import public_file
from administrative.public_file import ParseWord, PDFConverter
from django.db.models import Q, Count
from administrative.utils import send_mssage
from administrative.search_data import SearchData
from django.db import connection
import xlrd2 as xlrd
import uuid
# Create your views here.

# 行政首页 我先测试一下更换git文件是否可以 我再测试一下
from Administrative_office_system.utils.views import LoginRequiredMixin
from back_management.models import topic_meeting
from personal_center.models import User, SealApply, SealApplyAuditRecord, MakeCopy
import datetime

from system_setup.models import CustomerFormModule
from union_process.models import PaymentProcess, PaymentProcessRecord, EconomicCountersign, EconomicCountersignRecord


def search_prople_DZ(job_number):
    """查询党政办公室人员工号, 查询是否是普通职员"""
    # data_quer = User.objects.filter(Q(department="医院办公室") | Q(department="党委办公室") | Q(level=1)  | Q(level=2) | Q(level=4))
    data_quer = User.objects.filter(Q(department="医院办公室") | Q(department="党委办公室") | Q(level=1) | Q(level=2))
    job_number_list = []
    for i in data_quer:
        job_number_list.append(i.job_number)

    if job_number in job_number_list:
        return True
    else:
        return False


class home(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        if search_prople_DZ(request.user.job_number):
            search_flag = "True"
        else:
            search_flag = ""
        objs = post_single.objects.values('official_type').annotate(usercount=Count('id')).order_by("-usercount")
        obj_1 = official_serial_number.objects.values("number_type")
        type_list = [i["number_type"] for i in obj_1]
        obj_dict = {}
        post_single_num = 0
        for obj in objs:
            obj_dict[obj.get('official_type')] = obj.get('usercount')
            post_single_num += obj.get('usercount')
        for li in type_list:
            if li not in obj_dict:
                obj_dict[li] = 0
        car_num = application.objects.filter(form_name="用车申请").count()
        metting_num = application.objects.filter(form_name="会议申请").count()
        Iss_num = IssueApproval.objects.all().count()
        return render(request, 'administrative/home.html', {"staff_level": request.user.level, "search_flag": search_flag, "panduan": "True", 'realname': real_name, 'position': position, 'department': department, "flag": "", "obj_dict": [obj_dict],
                                                            "post_single_num": post_single_num, "car_num": car_num, "metting_num": metting_num, "Iss_num": Iss_num})


class UploadIssueFileView(LoginRequiredMixin, View):
    def get(self,request):
        delete_list = request.GET.get('delete_list')
        issue_id = request.GET.get('issue_number')
        if search_prople_DZ(request.user.job_number):
            search_flag = "True"
        else:
            search_flag = ""
        if not all([delete_list,issue_id]):
            returnDict = {'code': 400, 'status': '缺少必传参数', 'data': ''}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        try:
            file_path = IssueInfoFile.objects.get(id=delete_list).file_path
            uploader = IssueInfoFile.objects.get(id=delete_list).uploader
            # if request.user.username != uploader:
            #     returnDict = {'code': 400, 'status': '仅限上传人删除', 'data': ''}
            #     return HttpResponse(json.dumps(returnDict), content_type="application/json")

            file_name = '/' + str(file_path).split('/')[-1]
            file_dir = str(file_path).replace(file_name,'')
            sys_path = os.getcwd()
            sys_path = sys_path.replace('\\', '/')
            if sys_path == 'E:/':
                sys_path = 'E:/Pycharmproject/hospitalisoa'
            del_file_path = sys_path+'/media/'+str(file_dir)
            shutil.rmtree(os.path.realpath(del_file_path))
            IssueInfoFile.objects.get(id=delete_list).delete()
        except Exception as e:
            returnDict = {'code': 400, 'status': '删除失败', 'data': ''}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        issue_id = issue_id.replace('议题编号：', '').strip()
        all_objs = IssueInfoFile.objects.filter(Info_id=issue_id)
        data_li = []
        for i in all_objs:
            item = {}
            item['id'] = i.id
            item['file_path'] = '/media/' + str(i.file_path)
            item['file_name'] = str(i.file_path).split('/')[-1]
            item['file_size'] = i.file_size
            item['create_time'] = str(i.create_time).split('.')[0]
            try:
                item['uploader'] = User.objects.get(username=i.uploader).real_name
            except:
                item['uploader'] = i.uploader if i.uploader else ''
            item['file_type'] = '正文' if i.file_type == '0' else '附件'
            if str(i.file_path).split('.')[-1] in ['docx','pdf','PDF']:
                item['pdf_path'] = '/media/' + str(i.file_path).replace('.docx', '.pdf').replace('.doc', '.pdf')
            else:
                item['pdf_path'] = ''
            data_li.append(item)

        del_button = '0'
        try:
            issue_obj = IssueApproval.objects.get(issue_number=issue_id)
            if request.user.username == issue_obj.submitter:
                if issue_obj.submitter == issue_obj.now_flow:
                    if not issue_obj.to_do_list:
                        del_button = '1'
        except:
            del_button = '2'

        returnDict = {'code': 200, 'status': 'success', 'data': {'data_li':data_li,'del_button':del_button}}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


    def post(self,request):
        file1 = request.FILES.get('file1')
        file2 = request.FILES.get('file2')
        issue_id = request.POST.get('issue_number')
        if not issue_id:
            returnDict = {'code': 400, 'status': '缺少必传参数', 'data': []}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        issue_id = issue_id.replace('议题编号：', '').strip()
        if file1:
            if file1.name.split('.')[-1] not in ['docx','pdf','PDF']:
                returnDict = {'code': 400, 'status': '正文需为docx或pdf格式！', 'data': []}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")


            main_body_objs = IssueInfoFile.objects.filter(Info_id=issue_id, file_type='0')
            if main_body_objs.count() > 0:
                for main_body_obj in main_body_objs:
                    save_file_path = main_body_obj.file_path
                    obj_id = main_body_obj.id
                    sys_path = os.getcwd()
                    sys_path = sys_path.replace('\\', '/')
                    if sys_path == 'E:/':
                        sys_path = 'E:/Pycharmproject/hospitalisoa'
                    full_save_file_path = sys_path + '/media/' + str(save_file_path)
                    remove_path = full_save_file_path.replace('/' + full_save_file_path.split('/')[-1], '')
                    shutil.rmtree(remove_path)
                    IssueInfoFile.objects.get(id=obj_id).delete()

            try:
                issue_file_obj = IssueInfoFile.objects.create(
                    Info_id= issue_id,
                    file_path=file1,
                    file_size = public_file.StrOfSize(file1.size),
                    uploader = request.user.username,
                    file_type = '0'
                )
            except Exception as e:
                returnDict = {'code': 400, 'status': '上传正文失败', 'data': str(e)}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            file_path = str(issue_file_obj.file_path)
            if file_path.split('.')[-1] in ['docx','doc']:
                sys_path = os.getcwd()
                sys_path = sys_path.replace('\\','/')
                if sys_path == 'E:/':
                    sys_path = 'E:/Pycharmproject/hospitalisoa'
                new_path = sys_path +'/media/'+ file_path
                pdf_path = ParseWord().word2pdf(new_path)
                if pdf_path:
                    new_pdf_path = sys_path + pdf_path
                    file_name = new_path.split('/')[-1]
                    dis_path = new_path.replace(file_name,'')
                    shutil.move(new_pdf_path,dis_path)
                    copy_docx_path = new_path.replace('.docx','_new.docx')
                    if not os.path.exists(copy_docx_path):
                        shutil.copy(new_path,copy_docx_path)
                    remove_path = new_pdf_path.replace('/'+new_pdf_path.split('/')[-1],'')
                    shutil.rmtree(remove_path)


        if file2:
            try:
                issue_file_obj = IssueInfoFile.objects.create(
                    Info_id= issue_id,
                    file_path=file2,
                    file_size = public_file.StrOfSize(file2.size),
                    uploader = request.user.username,
                    file_type = '1'
                )
            except Exception as e:
                returnDict = {'code': 400, 'status': '上传附件失败', 'data': str(e)}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            file_path = str(issue_file_obj.file_path)
            if file_path.split('.')[-1] in ['docx','doc']:
                sys_path = os.getcwd()
                sys_path = sys_path.replace('\\','/')
                if sys_path == 'E:/':
                    sys_path = 'E:/Pycharmproject/hospitalisoa'
                new_path = sys_path +'/media/'+ file_path
                pdf_path = ParseWord().word2pdf(new_path)
                if pdf_path:
                    new_pdf_path = sys_path + pdf_path
                    file_name = new_path.split('/')[-1]
                    dis_path = new_path.replace(file_name,'')
                    shutil.move(new_pdf_path,dis_path)
                    copy_docx_path = new_path.replace('.docx','_new.docx')
                    if not os.path.exists(copy_docx_path):
                        shutil.copy(new_path,copy_docx_path)
                    remove_path = new_pdf_path.replace('/'+new_pdf_path.split('/')[-1],'')
                    shutil.rmtree(remove_path)



        all_objs = IssueInfoFile.objects.filter(Info_id=issue_id)
        data_li = []
        for i in all_objs:
            item = {}
            item['id'] = i.id
            item['download_path'] = '/media/' + str(i.file_path)
            item['file_name'] = str(i.file_path).split('/')[-1]
            if item['file_name'].split('.')[-1] in ['docx','doc']:
                item['file_path'] = '/media/' + str(i.file_path).replace('.docx','.pdf').replace('.doc','.pdf')
                item['download_path'] = '/media/' + str(i.file_path).replace('.docx','_new.docx')
            else:
                item['file_path'] = '/media/' + str(i.file_path)
            item['file_size'] = i.file_size
            item['create_time'] = str(i.create_time).split('.')[0]
            try:
                item['uploader'] = User.objects.get(username=i.uploader).real_name
            except:
                item['uploader'] = i.uploader if i.uploader else ''
            item['file_type'] = '正文' if i.file_type == '0' else '附件'
            if str(i.file_path).split('.')[-1] in ['docx','pdf','PDF']:
                item['pdf_path'] = '/media/' + str(i.file_path).replace('.docx', '.pdf').replace('.doc', '.pdf')
            else:
                item['pdf_path'] = ''
            data_li.append(item)
        del_button = '0'
        try:
            issue_obj = IssueApproval.objects.get(issue_number=issue_id)
            if request.user.username == issue_obj.submitter:
                if issue_obj.submitter == issue_obj.now_flow:
                    if not issue_obj.to_do_list:
                        del_button = '1'
        except:
            del_button = '2'

        returnDict = {'code': 200, 'status': 'success', 'data': {'data_li': data_li, 'del_button': del_button}}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TopicsView(View):
    def get(self, request):
        company_list = [{c.id: c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]
        returnDict = {'code': 200, 'message': '获取成功', 'company_list': company_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    # 议题提交创建
    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        number = request.POST.get('number', None)                   # 议题编号
        repones_uuid = request.POST.get('uuid', None)                   # 议题编号
        type_s = request.POST.get('type', None)                       # 议题类型：db、yb、xz
        topics_name = request.POST.get('topics_name', None)         # 议题名称
        topics_text = request.POST.get('topics_text', None)         # 议题内容
        topics_basis = request.POST.get('topics_basis', None)       # 议题依据
        solution = request.POST.get('solution', "空")           # 解决方案
        ysje_str = request.POST.get('ysje', None)           # 预算金额
        jfly_str = request.POST.get('jfly', None)             # 经费来源
        topics_estimate = request.POST.get('topics_estimate', None)
        help_department1 = request.POST.get('help_department', None)
        help_department = json.loads(help_department1) if help_department1 else ''  # ['1','2'] id列表
        is_yb_type = request.POST.get('is_yb', '2')                     # 是否经过院办
        nr_wenben = request.POST.get('nr_wenben', None)
        yj_wenben = request.POST.get('yj_wenben', None)
        fa_wenben = request.POST.get('fa_wenben', None)
        fg_people = request.POST.get('fg_people', None)  # 分管领导
        topic_type = request.POST.get('topic_type_select', '')                          # 议题类型
        pay_type = request.POST.get('pay_type_select', '')                          # 付款类型
        whether_outweigh = request.POST.get('whether_outweigh_20', '')           # 是否超过20万元
        Payee = request.POST.get('Payee', '')                                       # 收款单位
        receiving_account = request.POST.get('receiving_account', '')               # 收款账号
        opening_bank = request.POST.get('opening_bank', '')                         # 开户行

        contract_type_select = request.POST.get('contract_type_select', '')  # 合同类型
        contract_name = request.POST.get('contract_name', '')  # 合同名称
        contract_number = request.POST.get('contract_number', '')  # 合同编号

        transfer = request.POST.get("transfer", None)           # 是否为院办转党办
        topic_id = request.POST.get("id", None)                 # 院办转党办议题ＩＤ

        application_amount = request.POST.get('application_amount', '')  # 申请金额
        amount_words = request.POST.get('amount_words', '')  # 金额大写
        funding_source = request.POST.get('funding_source', '')  # 经费来源

        received_id = request.POST.get('received_id', '')  # 上级来文ID
        received_foreign = None
        if received_id:
            received_foreign = OfficialDocuments.objects.get(id=int(received_id))

        whether_bid = request.POST.get('whether_bid', '')  # 是否招标
        now_time = datetime.datetime.now().strftime("%Y")
        if transfer:            # 判断是否由院办转党办
            topic_obj = Topics.objects.get(id=topic_id)
            topic_meeting_number = topic_obj.meetings_num
            topic_uuid = uuid.uuid1()
            sequence_obj = Sequence.objects.filter(type='JYDB-'+topic_obj.number.split('-')[1], topic_year=str(now_time))

            if sequence_obj:
                print("取下一个编号")
                topic_number = f'0{sequence_obj[0].next_sequence}' if int(sequence_obj[0].next_sequence) < 10 else sequence_obj[0].next_sequence
            else:
                print("重置编号")
                topic_number = '01'
                Sequence.objects.create(type='JYDB-' + topic_obj.number.split('-')[1], topic_year=str(now_time), sequence=1, next_sequence=2)

            TopNumber = f"JYDB-{topic_obj.number.split('-')[1]}-{now_time}-{topic_number}"
            db_topic_obj = Topics.objects.create(
                            employee=topic_obj.employee, number=TopNumber, type='db', topics_name=topic_obj.topics_name, state='yb', company=request.user.company,
                            topics_text=topic_obj.topics_text, topic_type=topic_obj.topic_type, pay_type=topic_obj.pay_type, whether_outweigh=topic_obj.whether_outweigh,
                            topics_basis=topic_obj.topics_basis, Payee=topic_obj.Payee, receiving_account=topic_obj.receiving_account, opening_bank=topic_obj.opening_bank,
                            solution=topic_obj.solution,  funding_source=topic_obj.funding_source, amount_words=topic_obj.amount_words, application_amount=topic_obj.application_amount,
                            topics_estimate=topic_obj.topics_estimate, whether_bid=topic_obj.whether_bid, received_foreign=topic_obj.received_foreign,
                            is_yb=True, nrwb=topic_obj.nrwb, zcwb=topic_obj.zcwb, fawb=topic_obj.fawb, ysje=topic_obj.ysje, jfly=topic_obj.jfly,
                            uuid=topic_uuid, contract_type=topic_obj.contract_type, contract_name=topic_obj.contract_name, contract_number=topic_obj.contract_number,
                            HouseToParty_id=topic_obj.id
                        )
            # 协办科室
            help_department_list = topic_obj.help_department.all()
            for department in help_department_list:
                db_topic_obj.help_department.add(department)

            # 议题附件
            topic_file_list = Topicsattachments.objects.filter(topics_number=topic_obj.uuid)
            for files in topic_file_list:
                Topicsattachments.objects.create(
                    topics_number=topic_uuid,
                    file_path=files.file_path,
                    file_size=files.file_size,
                    uploader=files.uploader,
                    file_type='0',
                    is_deleted=files.is_deleted,
                    file_name=files.file_name,
                    pdf_path=files.pdf_path,
                    source='yt',
                    uploader_user=files.uploader_user
                )

            # 审批意见/详情
            Record_all = topic_obj.topicsauditrecord_set.all()
            for Record in Record_all:
                new_obj = TopicsAuditRecord.objects.create(topics_id=db_topic_obj, audit_people=Record.audit_people, audit_note=Record.audit_note, state=Record.state, node=Record.node)
                new_obj.update_time = Record.update_time
                new_obj.save()

            pg_step = Company.objects.get(id=3).head_people
            TopicsAuditRecord.objects.create(topics_id=db_topic_obj, audit_people=pg_step, audit_note='', state='unaudit', node='PG')
            db_topic_obj.current_audit_user = pg_step.real_name

            now_date = datetime.datetime.now().strftime('%Y-%m-%d')
            TransferOpinions = f"该议题于{now_date.split('-')[0]}年{now_date.split('-')[1]}月{now_date.split('-')[2]}日根据第{topic_meeting_number}次院长办公会提交党委会审议！"
            TopicsAuditRecord.objects.create(topics_id=db_topic_obj, audit_people=request.user, audit_note=TransferOpinions, state='audit', node='transfer')
            TopicsAuditRecord.objects.create(topics_id=topic_obj, audit_people=request.user, audit_note=TransferOpinions, state='audit', node='transfer')

            # 更新 议题编号表
            if sequence_obj:
                sequence_obj = sequence_obj.first()
                sequence_obj.sequence += 1
                sequence_obj.next_sequence += 1
                sequence_obj.save()

            topic_obj.is_yb = True
            topic_obj.save()

            db_topic_obj.state = "PG"
            db_topic_obj.save()

            MakeCopy.objects.create(recipient=db_topic_obj.employee, process_id=db_topic_obj.id, type='l')

            returnDict = {'code': 200, 'message': '创建成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        else:
            if is_yb_type == "1":
                is_yb_type = True
            if is_yb_type == "2":
                is_yb_type = False
            try:
                if user.company.abbreviation in ['YWK', 'DZB', 'YZB', 'SJK']:
                    current_audit_user = ""
                    if fg_people:
                        fg_people_obj = User.objects.get(id=int(fg_people))
                        current_audit_user = fg_people_obj.real_name
                else:
                    current_audit_user = user.company.leaders_id.real_name
                if not id:
                    topics_obj = Topics.objects.create(employee=user, number=number, type=type_s, topics_name=topics_name.strip(), company=request.user.company,
                                                       topics_text=base64.b64encode(topics_text.encode("utf-8")).decode(), received_foreign=received_foreign,
                                                       topics_basis=base64.b64encode(topics_basis.encode("utf-8")).decode() if topics_basis else '',
                                                       solution=base64.b64encode(solution.encode("utf-8")).decode() if solution else '',
                                                       topics_estimate=topics_estimate, pay_type=pay_type, whether_outweigh=whether_outweigh,
                                                       current_audit_user=current_audit_user, Payee=Payee, receiving_account=receiving_account, opening_bank=opening_bank,
                                                       is_yb=is_yb_type, topic_type=topic_type, contract_type=contract_type_select, contract_name=contract_name, contract_number=contract_number,
                                                       nrwb=nr_wenben, application_amount=application_amount, amount_words=amount_words, funding_source=funding_source,
                                                       iss_year=datetime.datetime.now().year, whether_bid=whether_bid,
                                                       zcwb=yj_wenben if yj_wenben else "",
                                                       fawb=fa_wenben if fa_wenben else "",
                                                       ysje=ysje_str,
                                                       jfly=jfly_str,
                                                       uuid=repones_uuid)
                else:
                    topics_obj = Topics.objects.get(id=int(id))
                    topics_obj.topics_name = topics_name.strip()
                    topics_obj.number = number
                    topics_obj.pay_type = pay_type
                    topics_obj.whether_outweigh = whether_outweigh
                    topics_obj.topic_type = topic_type
                    topics_obj.Payee = Payee
                    topics_obj.whether_bid = whether_bid
                    topics_obj.contract_type = contract_type_select
                    topics_obj.contract_name = contract_name
                    topics_obj.contract_number = contract_number
                    topics_obj.receiving_account = receiving_account
                    topics_obj.opening_bank = opening_bank
                    topics_obj.topics_text = base64.b64encode(topics_text.encode("utf-8")).decode()
                    topics_obj.topics_basis = base64.b64encode(topics_basis.encode("utf-8")).decode() if topics_basis else ''
                    topics_obj.solution = base64.b64encode(solution.encode("utf-8")).decode() if solution else ''
                    topics_obj.topics_estimate = topics_estimate
                    topics_obj.nrwb = nr_wenben
                    topics_obj.zcwb = yj_wenben if yj_wenben else ""
                    topics_obj.fawb = fa_wenben if fa_wenben else ""
                    topics_obj.ysje = ysje_str
                    topics_obj.jfly = jfly_str
                    topics_obj.application_amount = application_amount
                    topics_obj.amount_words = amount_words
                    topics_obj.funding_source = funding_source
                    topics_obj.state = 'draft'
                    topics_obj.current_audit_user = current_audit_user
                    topics_obj.save()
                if fg_people:
                    topics_obj.fg_people_id = int(fg_people)
                    topics_obj.save()
                temp_list = topics_obj.number.split('-')[0:2]
                temp_number = '-'.join(temp_list)
                sequence_obj = Sequence.objects.filter(type=temp_number, topic_year=now_time)
                if sequence_obj:
                    sequence_obj = sequence_obj.first()
                    sequence_obj.sequence += 1
                    sequence_obj.next_sequence += 1
                    sequence_obj.save()
                else:
                    Sequence.objects.create(type=temp_number, sequence=1, next_sequence=2, topic_year=now_time)

                for company_id in help_department:
                    com = Company.objects.get(id=int(company_id.replace("(", "").replace(")", "")))
                    topics_obj.help_department.add(com)

                if topics_obj.received_foreign:
                    topics_obj.received_foreign.topOrappave = '1'
                    topics_obj.received_foreign.top_flow_id = topics_obj
                    topics_obj.received_foreign.save()

            except Exception as e:
                print(e)
                returnDict = {'code': 500, 'message': '创建错误！请联系管理员！'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            else:
                if user.company.id in [13, 3, 22]:
                    if fg_people:
                        fg_people_obj = User.objects.get(id=int(fg_people))
                    else:
                        returnDict = {'code': 500, 'message': '需要选择分管领导！'}
                        return HttpResponse(json.dumps(returnDict), content_type="application/json")
                elif user.company.id == 80:
                    if type_s == "yb":
                        fg_people_obj = ""
                    else:
                        fg_people_obj = User.objects.get(id=int(fg_people))
                else:
                    fg_people_obj = user.company.leaders_id

                if topics_obj.type == 'db':
                    TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=fg_people_obj, audit_note='', state='unaudit', node='B')
                    TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Company.objects.get(id=3).head_people, audit_note='', state='unaudit', node='YB/DB')
                    TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Company.objects.get(id=3).leaders_id, audit_note='', state='unaudit', node='Y_D_leader')
                    TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Staffing.objects.get(station="书记").post_personnel.all().first(), audit_note='', state='unaudit', node='YZ/SJ')
                else:
                    if type_s == "xz":
                        if request.user.company.id != 80:
                            TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=fg_people_obj, audit_note='', state='unaudit', node='B')
                        else:
                            topics_obj.current_audit_user = Staffing.objects.get(station="院长").post_personnel.all().first().real_name
                            topics_obj.state = "audit"
                            topics_obj.save()
                        TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), audit_note='', state='unaudit', node='YZ/SJ')
                        TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Company.objects.get(id=80).head_people, audit_note='', state='unaudit', node='YB/DB')
                    else:
                        if user.company.id != 80:
                            TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=fg_people_obj, audit_note='', state='unaudit', node='B')
                        else:
                            topics_obj.state = 'OPR'
                            topics_obj.current_audit_user = User.objects.get(job_number="9770").real_name
                        if type_s == 'yb':
                            TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=User.objects.get(job_number="9770"), audit_note='', state='unaudit', node='OPR')
                        TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Company.objects.get(id=80).head_people, audit_note='', state='unaudit', node='YB/DB')
                        TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), audit_note='', state='unaudit', node='YZ/SJ')

                topics_obj.save()
                topic_type = "院办议题" if topics_obj.type == "yb" else "党办议题" if topics_obj.type == "db" else "行政例会"
                applicant = topics_obj.employee.real_name
                ApplicationTime = topics_obj.create_time.strftime("%Y-%m-%d %H:%M")
                SubjectMatter = topics_obj.topics_name[:15] + "……" if len(topics_obj.topics_name) > 15 else topics_obj.topics_name
                try:
                    RecordAndPush().MessagePush(User.objects.filter(real_name=topics_obj.current_audit_user).first().openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
                returnDict = {'code': 200, 'message': '创建成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TopicsDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            print(E)
            return redirect("/")
        returndata = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in returndata:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)
        ids = request.GET.get("id", None)
        obj = Topics.objects.get(id=int(ids))
        abbreviation = request.user.company.abbreviation
        now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
        now_year = now_time.split('-')[0]
        top_type = "JYDB-" if obj.type == 'db' else "JYYB-" if obj.type == 'yb' else "JYXZLH-"

        db_obj = Sequence.objects.filter(type=top_type + abbreviation, topic_year=now_year)
        if db_obj:
            db_obj = db_obj.first()
            db_num = str(db_obj.next_sequence).zfill(2)
        else:
            db_num = '01'

        Serial_number = top_type + abbreviation + "-" + now_year + "-" + db_num
        objs_count = 'true' if Topics.objects.get(id=int(ids)).topicsauditrecord_set.filter(
            node='PG').count() else 'false'
        objs_dict = {
            'topics_text': base64.b64decode(obj.topics_text).decode(),
            'topics_basis': base64.b64decode(obj.topics_basis).decode(),
            'solution': base64.b64decode(obj.solution).decode() if obj.solution != "空" else "",
            'db_topics_text': base64.b64decode(obj.db_topics_text).decode() if obj.db_topics_text else "",
            'db_topics_basis': base64.b64decode(obj.db_topics_basis).decode() if obj.db_topics_basis else "",
            'db_solution': base64.b64decode(obj.db_solution).decode() if obj.db_solution else "",
        }

        audit_dic = {}
        for audit_obj in obj.topicsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        leaders = User.objects.filter(group_id=2, is_delete=False)
        return render(request, "personal_center/topics_draft.html",
                      {'realname': real_name, 'position': position, 'department': department, "zbb_flag": "true" if request.user.company.id == 9 else "false",
                       "company_list": company_list, "objs_count": objs_count, "obj": obj, "objs_dict": objs_dict, 'received_obj': obj.received_foreign if obj.received_foreign else '',
                       "audit_dic": audit_dic, "leaders": leaders, "Serial_number": Serial_number, 'uuid': obj.uuid})

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        number = request.POST.get('number', None)  # 议题编号
        repones_uuid = request.POST.get('uuid', None)  # 议题编号
        type_s = request.POST.get('type', None)  # 议题类型：db、yb、xz
        topics_name = request.POST.get('topics_name', None)  # 议题名称
        topics_text = request.POST.get('topics_text', None)  # 议题内容
        topics_basis = request.POST.get('topics_basis', None)  # 议题依据
        solution = request.POST.get('solution', "空")  # 解决方案
        ysje_str = request.POST.get('ysje', None)  # 预算金额
        jfly_str = request.POST.get('jfly', None)  # 经费来源
        topics_estimate = request.POST.get('topics_estimate', None)
        help_department1 = request.POST.get('help_department', None)
        help_department = json.loads(help_department1) if help_department1 else ''  # ['1','2'] id列表
        is_yb_type = request.POST.get('is_yb', '2')  # 是否经过院办
        nr_wenben = request.POST.get('nr_wenben', None)
        yj_wenben = request.POST.get('yj_wenben', None)
        fa_wenben = request.POST.get('fa_wenben', None)
        fg_people = request.POST.get('fg_people', None)  # 分管领导
        topic_type = request.POST.get('topic_type_select', '')  # 议题类型
        pay_type = request.POST.get('pay_type_select', '')  # 付款类型
        whether_outweigh = request.POST.get('whether_outweigh_20', '')  # 是否超过20万元
        Payee = request.POST.get('Payee', '')                            # 收款单位

        contract_type = request.POST.get('contract_type_select', '')  # 合同类型
        contract_name = request.POST.get('contract_name', '')
        contract_number = request.POST.get('contract_number', '')

        receiving_account = request.POST.get('receiving_account', '')                   # 收款账号
        opening_bank = request.POST.get('opening_bank', '')                             # 开户行

        application_amount = request.POST.get('application_amount', '')                 # 申请金额
        amount_words = request.POST.get('amount_words', '')                 # 金额大写
        funding_source = request.POST.get('funding_source', '')         # 经费来源
        whether_bid = request.POST.get('whether_bid', '')                   # 是否招标

        received_id = request.POST.get('received_id', '')  # 上级来文ID
        received_foreign = None
        if received_id:
            received_foreign = OfficialDocuments.objects.get(id=int(received_id))
        if not id:
            topics_obj = Topics.objects.create(employee=user, type=type_s, topics_name=topics_name, company=request.user.company,
                                               topics_text=base64.b64encode(topics_text.encode("utf-8")).decode(), received_foreign=received_foreign,
                                               topics_basis=base64.b64encode(topics_basis.encode("utf-8")).decode() if topics_basis else '',
                                               solution=base64.b64encode(solution.encode("utf-8")).decode() if solution else '',
                                               topics_estimate=topics_estimate, Payee=Payee, receiving_account=receiving_account, opening_bank=opening_bank,
                                               is_yb=False if is_yb_type == '2' else True,
                                               nrwb=nr_wenben, topic_type=topic_type, pay_type=pay_type, whether_outweigh=whether_outweigh,
                                               zcwb=yj_wenben if yj_wenben else "", whether_bid=whether_bid,
                                               fawb=fa_wenben if fa_wenben else "",
                                               ysje=ysje_str, funding_source=funding_source, amount_words=amount_words,
                                               jfly=jfly_str, application_amount= application_amount,
                                               uuid=repones_uuid,
                                               contract_type=contract_type,
                                               contract_name=contract_name,
                                               contract_number=contract_number,
                                               state='cg'
                                               )

        else:
            topics_obj = Topics.objects.get(id=int(id))
            topics_obj.topics_name = topics_name
            topics_obj.topics_text = base64.b64encode(topics_text.encode("utf-8")).decode()
            topics_obj.topics_basis = base64.b64encode(topics_basis.encode("utf-8")).decode() if topics_basis else ''
            topics_obj.solution = base64.b64encode(solution.encode("utf-8")).decode() if solution else ''
            topics_obj.topics_estimate = topics_estimate
            topics_obj.whether_bid = whether_bid
            topics_obj.nrwb = nr_wenben
            topics_obj.zcwb = yj_wenben
            topics_obj.fawb = fa_wenben
            topics_obj.ysje = ysje_str
            topics_obj.jfly = jfly_str
            topics_obj.topic_type = topic_type
            topics_obj.pay_type = pay_type
            topics_obj.contract_type = contract_type
            topics_obj.contract_name = contract_name
            topics_obj.contract_number = contract_number
            topics_obj.whether_outweigh = whether_outweigh
            topics_obj.Payee = Payee
            topics_obj.receiving_account = receiving_account
            topics_obj.opening_bank = opening_bank
            topics_obj.funding_source = funding_source
            topics_obj.amount_words = amount_words
            topics_obj.application_amount = application_amount
            topics_obj.save()

        if fg_people:
            topics_obj.fg_people_id = int(fg_people)
            topics_obj.save()
        for company_id in help_department:
            com = Company.objects.get(id=company_id)
            topics_obj.help_department.add(com)
        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TopicsDetailView(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get('id', None)
        try:
            topics_obj = Topics.objects.get(id=int(id))
        except Exception as e:
            print(e)
            returnDict = {'code': 500, 'message': '获取详情失败'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            audit_dic = {}
            for audit_obj in topics_obj.topicsauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.get_state_display(),
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.get_state_display(),
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
            main_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path,
                 "pdf_path": atta_obj.pdf_path,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size,
                 "uploader": atta_obj.uploader_user.real_name if atta_obj.uploader_user else request.user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for
                atta_obj in
                Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0")]

            help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
            help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])
            data_dic = {'apply_user': topics_obj.employee.real_name,
                        'department': topics_obj.employee.company.name,
                        'state': topics_obj.get_state_display(),
                        'main_file_list': main_file_list,
                        'number': topics_obj.number,
                        'topics_name': topics_obj.topics_name,
                        'topics_text': base64.b64decode(topics_obj.topics_text).decode(),
                        'topics_basis': base64.b64decode(topics_obj.topics_basis).decode(),
                        'solution': base64.b64decode(topics_obj.solution).decode() if topics_obj.solution != "空" else "",
                        'topics_estimate': topics_obj.topics_estimate,
                        'help_department': help_department,
                        'help_department1': help_department1,
                        'jfly': topics_obj.jfly if topics_obj.jfly else "",
                        'ysje': topics_obj.ysje if topics_obj.ysje else "",
                        'uuid': topics_obj.uuid,
                        'audit_list': audit_dic,
                        'is_stop': 'true' if topics_obj.state in ['draft', 'confirm', 'audit', 'refuse', 'sj'] and request.user == topics_obj.employee else 'false',
                        'is_cancel': 'true' if topics_obj.state == 'done' and request.user == topics_obj.employee else 'false',
                        'is_recall': 'true' if topics_obj.topicsauditrecord_set.filter(state__in=['draft', 'audit']).count() == 0 and request.user == topics_obj.employee and topics_obj.state not in [
                                                   'stop', 'recall'] else 'false',
                        'is_audit': 'true' if topics_obj.state not in ['refuse', 'yb'] and topics_obj.current_audit_user == request.user.real_name else 'false',
                        'is_yb': 'true' if topics_obj.is_yb == 1 else 'false'
                        }
            returnDict = {'code': 200, 'message': '创建成功', 'data_dic': data_dic}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):        # 议题审核
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        if not state:
            returnData = {'code': 500, 'message': '参数错误，请联系管理员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        # try:
        topics_obj = Topics.objects.get(id=int(id))
        if topics_obj.type == "xz":
            if topics_obj.state == 'draft':
                if not topics_obj.topicsauditrecord_set.filter(node='B', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='B', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    topics_state = 'audit'
                    topics_obj.current_audit_user = Staffing.objects.get(station="院长").post_personnel.all().first().real_name

                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'confirm':
                if not topics_obj.topicsauditrecord_set.filter(node='YB/DB', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='YB/DB', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    topics_state = 'unmetting'
                    topics_obj.current_audit_user = ''
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'audit':
                if not topics_obj.topicsauditrecord_set.filter(node='YZ/SJ', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='YZ/SJ', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    topics_state = 'confirm'
                    dbzr = topics_obj.topicsauditrecord_set.filter(node='YB/DB', state='unaudit').first().audit_people
                    topics_obj.current_audit_user = dbzr.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            else:
                returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            if topics_obj.state == 'draft':
                if not topics_obj.topicsauditrecord_set.filter(node='B', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='B', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    if topics_obj.type == "yb" and topics_obj.topicsauditrecord_set.filter(node='OPR'):
                        topics_state = 'OPR'
                        topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='OPR', state='unaudit').first().audit_people.real_name
                    else:
                        topics_state = 'confirm'
                        topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='YB/DB', state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'OPR':
                if not topics_obj.topicsauditrecord_set.filter(node='OPR', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='OPR', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    topics_state = 'confirm'
                    topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='YB/DB', state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'confirm':
                if not topics_obj.topicsauditrecord_set.filter(node='YB/DB', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='YB/DB', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    one_record = topics_obj.topicsauditrecord_set.filter(node='B').first()
                    two_step = topics_obj.topicsauditrecord_set.filter(node='Y_D_leader')
                    if two_step:
                        two_record = topics_obj.topicsauditrecord_set.filter(node='Y_D_leader', state='unaudit').first()
                        if one_record and one_record.audit_people == two_record.audit_people:
                            two_record.update_time = datetime.datetime.now()
                            two_record.state = state
                            two_record.audit_note = audit_note
                            two_record.save()
                            topics_state = 'audit'
                            topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='YZ/SJ', state='unaudit').first().audit_people.real_name
                        else:
                            topics_state = 'yd_leader'
                            topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='Y_D_leader', state='unaudit').first().audit_people.real_name
                    else:
                        topics_state = 'audit'
                        topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='YZ/SJ', state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'yd_leader':
                if not topics_obj.topicsauditrecord_set.filter(node='Y_D_leader', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='Y_D_leader', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    topics_state = 'audit'
                    topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='YZ/SJ', state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'audit':
                if not topics_obj.topicsauditrecord_set.filter(node='YZ/SJ', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='YZ/SJ', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    topics_state = 'unmetting'
                    topics_obj.current_audit_user = ''
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'db_leader':
                if not topics_obj.topicsauditrecord_set.filter(node='db_leader', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='db_leader', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    topics_state = 'sj'
                    topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='sj', state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'sj':
                if not topics_obj.topicsauditrecord_set.filter(node='sj', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='sj', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    topics_state = 'unmetting'
                    topics_obj.current_audit_user = ''
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'PG':
                if not topics_obj.topicsauditrecord_set.filter(node='PG', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='PG', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    topics_state = 'sj'
                    TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Staffing.objects.get(station="书记").post_personnel.all().first(), audit_note='', state='unaudit', node='sj')
                    topics_obj.current_audit_user = Staffing.objects.get(station="书记").post_personnel.all().first().real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'db_one_step':
                if not topics_obj.topicsauditrecord_set.filter(node='db_one_step', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='db_one_step', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    topics_state = 'db_two_step'
                    topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='db_two_step', state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'db_two_step':
                if not topics_obj.topicsauditrecord_set.filter(node='db_two_step', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='db_two_step', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    one_appave = topics_obj.topicsauditrecord_set.filter(node='db_one_step').first()
                    three_appave = topics_obj.topicsauditrecord_set.filter(node='db_three_step').first()
                    if one_appave.audit_people == three_appave.audit_people:
                        topics_state = 'sj'
                        topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='sj', state='unaudit').first().audit_people.real_name
                        three_appave.update_time = one_appave.update_time
                        three_appave.state = one_appave.state
                        three_appave.audit_note = one_appave.audit_note
                        three_appave.save()
                    else:
                        topics_state = 'db_three_step'
                        topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='db_three_step', state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'db_three_step':
                if not topics_obj.topicsauditrecord_set.filter(node='db_three_step', state='unaudit', audit_people=request.user).count():
                    returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = topics_obj.topicsauditrecord_set.filter(node='db_three_step', state='unaudit', audit_people=request.user).first()
                if state == 'audit':
                    topics_state = 'sj'
                    topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='sj', state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            else:
                returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        topics_obj.state = topics_state
        topics_obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()

        if request.user not in topics_obj.already_users.all():
            topics_obj.already_users.add(request.user)
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


def DirectTransfer(topic_id, request):
    now_time = datetime.datetime.now().strftime("%Y")
    topic_obj = Topics.objects.get(id=topic_id)
    topic_meeting_number = topic_obj.meetings_num
    topic_uuid = uuid.uuid1()
    sequence_obj = Sequence.objects.filter(type='JYDB-' + topic_obj.number.split('-')[1], topic_year=str(now_time))

    if sequence_obj:
        print("取下一个编号")
        topic_number = f'0{sequence_obj[0].next_sequence}' if int(sequence_obj[0].next_sequence) < 10 else sequence_obj[0].next_sequence
    else:
        print("重置编号")
        topic_number = '01'
        Sequence.objects.create(type='JYDB-' + topic_obj.number.split('-')[1], topic_year=str(now_time), sequence=1, next_sequence=2)

    TopNumber = f"JYDB-{topic_obj.number.split('-')[1]}-{now_time}-{topic_number}"
    db_topic_obj = Topics.objects.create(application_amount=topic_obj.application_amount, received_foreign=topic_obj.received_foreign,
        employee=topic_obj.employee, number=TopNumber, type='db', topics_name=topic_obj.topics_name, state='yb', company=request.user.company,
        topics_text=topic_obj.topics_text, topic_type=topic_obj.topic_type, pay_type=topic_obj.pay_type, whether_outweigh=topic_obj.whether_outweigh,
        topics_basis=topic_obj.topics_basis, Payee=topic_obj.Payee, receiving_account=topic_obj.receiving_account, opening_bank=topic_obj.opening_bank,
        solution=topic_obj.solution, funding_source=topic_obj.funding_source, amount_words=topic_obj.amount_words, topics_estimate=topic_obj.topics_estimate,
        whether_bid=topic_obj.whether_bid, is_yb=True, nrwb=topic_obj.nrwb, zcwb=topic_obj.zcwb, fawb=topic_obj.fawb, ysje=topic_obj.ysje, jfly=topic_obj.jfly,
        uuid=topic_uuid, contract_type=topic_obj.contract_type, contract_name=topic_obj.contract_name, contract_number=topic_obj.contract_number, HouseToParty_id=topic_obj.id
    )

    if db_topic_obj.received_foreign:
        db_topic_obj.received_foreign.top_db_flow_id = db_topic_obj
        db_topic_obj.received_foreign.save()

    # 协办科室
    help_department_list = topic_obj.help_department.all()
    for department in help_department_list:
        db_topic_obj.help_department.add(department)

    # 议题附件
    topic_file_list = Topicsattachments.objects.filter(topics_number=topic_obj.uuid)
    for files in topic_file_list:
        Topicsattachments.objects.create(
            topics_number=topic_uuid, file_path=files.file_path, file_size=files.file_size, uploader=files.uploader, file_type='0', is_deleted=files.is_deleted,
            file_name=files.file_name, pdf_path=files.pdf_path, source='yt', uploader_user=files.uploader_user
        )

    # 审批意见/详情
    Record_all = topic_obj.topicsauditrecord_set.all()
    for Record in Record_all:
        new_obj = TopicsAuditRecord.objects.create(topics_id=db_topic_obj, audit_people=Record.audit_people, audit_note=Record.audit_note, state=Record.state, node=Record.node)
        new_obj.update_time = Record.update_time
        new_obj.save()

    pg_step = Company.objects.get(id=3).head_people
    TopicsAuditRecord.objects.create(topics_id=db_topic_obj, audit_people=pg_step, audit_note='', state='unaudit', node='PG')
    db_topic_obj.current_audit_user = pg_step.real_name

    now_date = datetime.datetime.now().strftime('%Y-%m-%d')
    TransferOpinions = f"该议题于{now_date.split('-')[0]}年{now_date.split('-')[1]}月{now_date.split('-')[2]}日根据第{topic_meeting_number}次院长办公会提交党委会审议！"
    TopicsAuditRecord.objects.create(topics_id=db_topic_obj, audit_people=request.user, audit_note=TransferOpinions, state='audit', node='transfer')
    TopicsAuditRecord.objects.create(topics_id=topic_obj, audit_people=request.user, audit_note=TransferOpinions, state='audit', node='transfer')

    # 更新 议题编号表
    if sequence_obj:
        sequence_obj = sequence_obj.first()
        sequence_obj.sequence += 1
        sequence_obj.next_sequence += 1
        sequence_obj.save()

    topic_obj.is_yb = True
    topic_obj.save()

    db_topic_obj.state = "PG"
    db_topic_obj.save()

    MakeCopy.objects.create(recipient=db_topic_obj.employee, process_id=db_topic_obj.id, type='l')

    returnDict = {'code': 200, 'message': '创建成功'}
    return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TopicsResult(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过 unaudit 不通过
        meeting_audit_note = request.POST.get("audit_note", None)  # 意见
        fujian_uuid = request.POST.get("uuid", '')  # 附件UUID
        TransferOrNot = request.POST.get("TransferOrNot", '')
        if not state:
            returnData = {'code': 500, 'message': '参数错误，请联系管理员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        topics_obj = Topics.objects.get(id=int(id))
        if not topics_obj.is_audit:
            returnData = {'code': 500, 'message': '该议题已通过,请勿重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        if topics_obj.state == 'metting':
            if state == 'audit':
                if topics_obj.type == 'db':
                    result_node = "db_result"
                    audit_note = '通过%s年第%s次党委会，与会人员经讨论该议题原则上通过，会议要求详见本次党委会会议纪要' % (str(datetime.datetime.now().year), topics_obj.meetings_num)
                elif topics_obj.type == 'yb':
                    result_node = "yb_result"
                    audit_note = '通过%s年第%s次院长办公会，与会人员经讨论该议题原则上通过，会议要求详见本次院长办公会会议纪要' % (str(datetime.datetime.now().year), topics_obj.meetings_num)
                else:
                    result_node = "xz_result"
                    audit_note = '通过%s年第%s次行政例会' % (str(datetime.datetime.now().year), topics_obj.meetings_num)
                if meeting_audit_note:
                    audit_note += ';%s' % meeting_audit_note
                TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=request.user, audit_note=audit_note, state='audit', node=result_node)
                topics_obj.is_audit = False
                topics_obj.state = 'done'
                topics_obj.save()
                try:
                    y_to_d = Topics.objects.get(HouseToParty_id=id)
                    yb_result_obj = y_to_d.topicsauditrecord_set.filter(node="yb_result")
                    yb_result_obj.audit_note = audit_note
                    yb_result_obj.save()
                except:
                    pass

                #****************************** 开始创建付款流程 ******************************
                if topics_obj.type == 'yb':
                    if TransferOrNot == '0':
                        if topics_obj.topic_type == "1":
                            if topics_obj.pay_type == '8':
                                PaymentObj = PaymentProcess.objects.create(apply_user=topics_obj.employee, company=topics_obj.employee.company, topics_id=topics_obj, reason=topics_obj.topics_name, fj_number=uuid.uuid4(), source="7", payee=topics_obj.Payee,
                                                                    bank=topics_obj.opening_bank, account_number=topics_obj.receiving_account, money_capital=topics_obj.amount_words, total_amount=topics_obj.application_amount, pay_type="8")
                                two_setp = Company.objects.get(id=7).head_people
                                PaymentProcessRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=PaymentObj)
                                PaymentObj.state = 'two'
                                PaymentObj.save()
                                PaymentObj.current_audit_users.add(two_setp)

                                three_setp = Staffing.objects.get(station='工会会计').post_personnel.all().first()
                                PaymentProcessRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=PaymentObj)

                                four_setp = Company.objects.get(id=23).head_people
                                PaymentProcessRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=PaymentObj)

                                five_setp = Staffing.objects.get(station='工会主席').post_personnel.all().first()
                                PaymentProcessRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=PaymentObj)

                                six_setp = Staffing.objects.get(station='工会经费支付').post_personnel.all().first()
                                PaymentProcessRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=PaymentObj)
                            else:
                                pay_obj = PaymentApproval.objects.create(apply_user=topics_obj.employee, company=topics_obj.employee.company, topics_id=topics_obj, state="three", title=topics_obj.topics_name, fj_number=uuid.uuid4())
                                PaymentApprovalRecord.objects.create(official_documents_id=pay_obj, audit_people=Company.objects.get(id=23).head_people, node="three")
                                PaymentApprovalRecord.objects.create(official_documents_id=pay_obj, audit_people=Staffing.objects.get(station="总会计师").post_personnel.all().first(), node="four")
                                PaymentApprovalRecord.objects.create(official_documents_id=pay_obj, audit_people=Staffing.objects.get(station="财务支付").post_personnel.all().first(), node="five")
                                pay_obj.state = "three"
                                pay_obj.current_audit_users.add(Company.objects.get(id=23).head_people)
                                pay_obj.save()

                                if topics_obj.received_foreign:
                                    topics_obj.received_foreign.pay_flow_id = pay_obj
                                    topics_obj.received_foreign.save()

                        if topics_obj.topic_type == "2" or topics_obj.topic_type == "7":
                            trade_union_obj = Company.objects.get(id=7)
                            gh_leader = trade_union_obj.head_people
                            if trade_union_obj in topics_obj.help_department.all() or gh_leader == topics_obj.employee:
                                EconomicObj = EconomicCountersign.objects.create(apply_user=topics_obj.employee, company=topics_obj.employee.company, topics_id=topics_obj, other_unit=topics_obj.Payee, fj_number=uuid.uuid4(),
                                                                         contract_name=topics_obj.topics_name, contract_number=topics_obj.contract_number, note="")
                                one_step = Company.objects.get(id=7).head_people
                                EconomicCountersignRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=EconomicObj)
                                EconomicObj.state = 'one'
                                EconomicObj.save()
                                EconomicObj.current_audit_users.add(one_step)

                                two_setp = Company.objects.get(id=23).head_people
                                EconomicCountersignRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=EconomicObj)

                                three_setp = Company.objects.get(id=18).head_people
                                EconomicCountersignRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=EconomicObj)

                                four_setp = Company.objects.get(id=22).head_people
                                EconomicCountersignRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=EconomicObj)

                                five_setp = Staffing.objects.get(station='工会主席').post_personnel.all().first()
                                EconomicCountersignRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=EconomicObj)

                                seven_setp = Company.objects.get(id=7).head_people
                                EconomicCountersignRecord.objects.create(node='six', audit_note='', audit_people=seven_setp, parent_id=EconomicObj)

                                eight_setp = Staffing.objects.get(station='工会印章管理员').post_personnel.all().first()
                                EconomicCountersignRecord.objects.create(node='seven', audit_note='', audit_people=eight_setp, parent_id=EconomicObj)

                            else:
                                contract_obj = ContractApproval.objects.create(apply_user=topics_obj.employee, topics_id=topics_obj, state="one", title=topics_obj.topics_name)
                                if topics_obj.topic_type == "7":
                                    ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=topics_obj.help_department.all().first().head_people, node="negative")
                                    ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=topics_obj.help_department.all().first().leaders_id, node="zero")
                                    contract_obj.state = "negative"
                                    contract_obj.current_audit_users.add(topics_obj.help_department.all().first().head_people)
                                else:
                                    ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=contract_obj.apply_user, node="six")
                                    ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=contract_obj.apply_user.company.leaders_id, node="zero")
                                    contract_obj.state = "six"
                                    contract_obj.current_audit_users.add(contract_obj.apply_user)
                                ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Company.objects.get(id=22).head_people, node="one")
                                ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Company.objects.get(id=23).head_people, node="two")
                                ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Company.objects.get(id=18).head_people, node="three")
                                ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), node="four")
                                ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Staffing.objects.get(station="印章管理员").post_personnel.all().first(), node="five")
                                contract_obj.save()

                        if topics_obj.topic_type == "3" and topics_obj.whether_bid == '1':
                            MakeCopy.objects.create(recipient=Company.objects.get(id=9).head_people, process_id=topics_obj.id, type='l')

                        if topics_obj.received_foreign and topics_obj.topic_type != "1":
                            topics_obj.received_foreign.current_audit_users.clear()
                            topics_obj.received_foreign.audit_users_already.add(topics_obj.employee)
                            topics_obj.received_foreign.state = 'six'
                            topics_obj.received_foreign.type = "e"
                            topics_obj.received_foreign.save()

                    else:
                        topics_obj.whether_outweigh = '1'
                        topics_obj.save()
                        DirectTransfer(id, request)

                if topics_obj.type == 'db':
                    if topics_obj.topic_type == "1":
                        if topics_obj.pay_type == '8':
                            PaymentObj = PaymentProcess.objects.create(apply_user=topics_obj.employee, company=topics_obj.employee.company, topics_id=topics_obj, reason=topics_obj.topics_name, fj_number=uuid.uuid4(), source="7", payee=topics_obj.Payee,
                                                                       bank=topics_obj.opening_bank, account_number=topics_obj.receiving_account, money_capital=topics_obj.amount_words, total_amount=topics_obj.application_amount, pay_type="8")
                            two_setp = Company.objects.get(id=7).head_people
                            PaymentProcessRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=PaymentObj)
                            PaymentObj.state = 'two'
                            PaymentObj.save()
                            PaymentObj.current_audit_users.add(two_setp)

                            three_setp = Staffing.objects.get(station='工会会计').post_personnel.all().first()
                            PaymentProcessRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=PaymentObj)

                            four_setp = Company.objects.get(id=23).head_people
                            PaymentProcessRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=PaymentObj)

                            five_setp = Staffing.objects.get(station='工会主席').post_personnel.all().first()
                            PaymentProcessRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=PaymentObj)

                            six_setp = Staffing.objects.get(station='工会经费支付').post_personnel.all().first()
                            PaymentProcessRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=PaymentObj)
                        else:
                            pay_obj = PaymentApproval.objects.create(apply_user=topics_obj.employee, company=topics_obj.employee.company, topics_id=topics_obj, state="three", title=topics_obj.topics_name, fj_number=uuid.uuid4())
                            PaymentApprovalRecord.objects.create(official_documents_id=pay_obj, audit_people=Company.objects.get(id=23).head_people, node="three")
                            PaymentApprovalRecord.objects.create(official_documents_id=pay_obj, audit_people=Staffing.objects.get(station="总会计师").post_personnel.all().first(), node="four")
                            PaymentApprovalRecord.objects.create(official_documents_id=pay_obj, audit_people=Staffing.objects.get(station="财务支付").post_personnel.all().first(), node="five")
                            pay_obj.state = "three"
                            pay_obj.current_audit_users.add(Company.objects.get(id=23).head_people)
                            pay_obj.save()

                            if topics_obj.received_foreign:
                                topics_obj.received_foreign.pay_flow_id = pay_obj
                                topics_obj.received_foreign.save()

                    if topics_obj.topic_type == "2" or topics_obj.topic_type == "7":
                        trade_union_obj = Company.objects.get(id=7)
                        gh_leader = trade_union_obj.head_people
                        if trade_union_obj in topics_obj.help_department.all() or gh_leader == topics_obj.employee:
                            EconomicObj = EconomicCountersign.objects.create(apply_user=topics_obj.employee, company=topics_obj.employee.company, topics_id=topics_obj, other_unit=topics_obj.Payee,
                                                                             fj_number=uuid.uuid4(), contract_name=topics_obj.topics_name, contract_number=topics_obj.contract_number, note="")
                            one_step = Company.objects.get(id=7).head_people
                            EconomicCountersignRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=EconomicObj)
                            EconomicObj.state = 'one'
                            EconomicObj.save()
                            EconomicObj.current_audit_users.add(one_step)

                            two_setp = Company.objects.get(id=23).head_people
                            EconomicCountersignRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=EconomicObj)

                            three_setp = Company.objects.get(id=18).head_people
                            EconomicCountersignRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=EconomicObj)

                            four_setp = Company.objects.get(id=22).head_people
                            EconomicCountersignRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=EconomicObj)

                            five_setp = Staffing.objects.get(station='工会主席').post_personnel.all().first()
                            EconomicCountersignRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=EconomicObj)

                            seven_setp = Company.objects.get(id=7).head_people
                            EconomicCountersignRecord.objects.create(node='six', audit_note='', audit_people=seven_setp, parent_id=EconomicObj)

                            eight_setp = Staffing.objects.get(station='工会印章管理员').post_personnel.all().first()
                            EconomicCountersignRecord.objects.create(node='seven', audit_note='', audit_people=eight_setp, parent_id=EconomicObj)

                        else:
                            contract_obj = ContractApproval.objects.create(apply_user=topics_obj.employee, topics_id=topics_obj, state="one", title=topics_obj.topics_name)
                            if topics_obj.topic_type == "7":
                                ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=topics_obj.help_department.all().first().head_people, node="negative")
                                ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=topics_obj.help_department.all().first().leaders_id, node="zero")
                                contract_obj.state = "negative"
                                contract_obj.current_audit_users.add(topics_obj.help_department.all().first().head_people)
                            else:
                                ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=contract_obj.apply_user, node="six")
                                ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=contract_obj.apply_user.company.leaders_id, node="zero")
                                contract_obj.state = "six"
                                contract_obj.current_audit_users.add(contract_obj.apply_user)
                            ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Company.objects.get(id=22).head_people, node="one")
                            ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Company.objects.get(id=23).head_people, node="two")
                            ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Company.objects.get(id=18).head_people, node="three")
                            ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), node="four")
                            ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Staffing.objects.get(station="印章管理员").post_personnel.all().first(), node="five")
                            contract_obj.save()

                    if topics_obj.topic_type == "3" and topics_obj.whether_bid == '1':
                        MakeCopy.objects.create(recipient=Company.objects.get(id=9).head_people, process_id=topics_obj.id, type='l')

                    if topics_obj.received_foreign and topics_obj.topic_type != "1":
                        topics_obj.received_foreign.current_audit_users.clear()
                        topics_obj.received_foreign.audit_users_already.add(topics_obj.employee)
                        topics_obj.received_foreign.state = 'six'
                        topics_obj.received_foreign.type = "e"
                        topics_obj.received_foreign.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'unaudit':
                if topics_obj.type == 'db':
                    result_node = "db_result"
                    audit_note = '未通过%s年第%s次党委会，与会人员经讨论该议题原则上不予通过，会议要求详见本次党委会会议纪要' % (str(datetime.datetime.now().year), topics_obj.meetings_num)
                elif topics_obj.type == 'yb':
                    result_node = "yb_result"
                    audit_note = '未通过%s年第%s次院长办公会，与会人员经讨论该议题原则上不予通过，会议要求详见本次院长办公会会议纪要' % (str(datetime.datetime.now().year), topics_obj.meetings_num)
                else:
                    result_node = "xz_result"
                    audit_note = '未通过%s年第%s次行政例会' % (str(datetime.datetime.now().year), topics_obj.meetings_num)
                if meeting_audit_note:
                    audit_note += ';%s' % meeting_audit_note
                TopicsAuditRecord.objects.create(topics_id=topics_obj,
                                                 audit_people=request.user,
                                                 audit_note=audit_note, state='draft', node=result_node)
                topics_obj.is_audit = False
                topics_obj.state = 'done'
                topics_obj.save()
                try:
                    y_to_d = Topics.objects.get(HouseToParty_id=id)
                    yb_result_obj = y_to_d.topicsauditrecord_set.filter(node="yb_result")
                    yb_result_obj.audit_note = audit_note
                    yb_result_obj.save()
                except:
                    pass
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                if topics_obj.type == 'db':
                    result_node = "db_result"
                    audit_note = '未通过%s年第%s次党委会，与会人员经讨论该议题原则上不予通过，会议要求详见本次党委会会议纪要' % (str(datetime.datetime.now().year), topics_obj.meetings_num)
                elif topics_obj.type == 'yb':
                    result_node = "yb_result"
                    audit_note = '未通过%s年第%s次院长办公会，与会人员经讨论该议题原则上不予通过，会议要求详见本次院长办公会会议纪要' % (str(datetime.datetime.now().year), topics_obj.meetings_num)
                else:
                    result_node = "xz_result"
                    audit_note = '未通过%s年第%s次行政例会' % (str(datetime.datetime.now().year), topics_obj.meetings_num)
                if meeting_audit_note:
                    audit_note += ';%s' % meeting_audit_note
                TopicsAuditRecord.objects.create(topics_id=topics_obj,
                                                 audit_people=request.user,
                                                 audit_note=audit_note, state='draft', node=result_node)

                new_topics_uuid = uuid.uuid1()
                new_topics_obj = Topics.objects.create(employee=topics_obj.employee, number=topics_obj.number,
                                                       type=topics_obj.type,
                                                       topics_name=topics_obj.topics_name,
                                                       topics_text=topics_obj.topics_text,
                                                       topics_basis=topics_obj.topics_basis,
                                                       solution=topics_obj.solution,
                                                       topics_estimate=topics_obj.topics_estimate,
                                                       current_audit_user=topics_obj.employee.real_name,
                                                       is_yb=topics_obj.is_yb,
                                                       nrwb=topics_obj.nrwb,
                                                       zcwb=topics_obj.zcwb,
                                                       fawb=topics_obj.fawb,
                                                       ysje=topics_obj.ysje,
                                                       jfly=topics_obj.jfly,
                                                       state='refuse',
                                                       uuid=new_topics_uuid,
                                                       create_time=topics_obj.create_time,
                                                       )
                for record in topics_obj.topicsauditrecord_set.all():
                    TopicsAuditRecord.objects.create(topics_id=new_topics_obj,
                                                     audit_people=record.audit_people,
                                                     audit_note=record.audit_note, state=record.state,
                                                     node=record.node, update_time=record.update_time)
                for item in Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0"):
                    Topicsattachments.objects.create(
                        topics_number=new_topics_obj.uuid,
                        file_path=item.file_path,
                        file_size=item.file_size,
                        uploader=item.uploader,
                        file_type='0',
                        is_deleted=item.is_deleted,
                        file_name=item.file_name,
                        pdf_path=item.pdf_path,
                        source='yt'
                    )
                topics_obj.is_audit = False
                topics_obj.state = 'done'
                topics_obj.save()
                try:
                    y_to_d = Topics.objects.get(HouseToParty_id=id)
                    yb_result_obj = y_to_d.topicsauditrecord_set.filter(node="yb_result")
                    yb_result_obj.audit_note = audit_note
                    yb_result_obj.save()
                except:
                    pass
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            returnData = {'code': 500, 'message': '只有已上会状态才能结束！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class TopicsWriteDetailView(View):
    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        type_s = request.POST.get('type', None)  # 议题类型：db、yb、xz
        topics_name = request.POST.get('topics_name', None)  # 议题名称
        topics_text = request.POST.get('topics_text', None)  # 议题内容
        topics_basis = request.POST.get('topics_basis', None)  # 议题依据
        solution = request.POST.get('solution', None)  # 解决方案
        fg_people = request.POST.get('fg_people', None)  # 分管领导
        topics_estimate = request.POST.get('topics_estimate', None)
        nr_wenben = request.POST.get('nr_wenben', None)  # 议题内容文本
        yj_wenben = request.POST.get('yj_wenben', None)  # 议题依据文本
        fa_wenben = request.POST.get('fa_wenben', None)  # 解决方案文本
        ysje_str = request.POST.get('ysje', None)  # 预算金额
        jfly_str = request.POST.get('jfly', None)  # 经费来源
        PgCount = request.POST.get('PgCount', '')  # 经费来源
        topic_type = request.POST.get('topic_type_select', '')  # 议题类型
        pay_type = request.POST.get('pay_type_select', '')  # 付款类型
        whether_outweigh = request.POST.get('whether_outweigh_20', '')  # 是否超过20万元
        Payee = request.POST.get('Payee', '')  # 收款单位
        receiving_account = request.POST.get('receiving_account', '')  # 收款账号
        opening_bank = request.POST.get('opening_bank', '')  # 开户行
        adminxiugai = request.POST.get('admin', '')  # 管理员修改
        help_department = request.POST.get('help_department', None)  # ['1','2'] id列表
        contract_type_select = request.POST.get('contract_type_select', '')

        application_amount = request.POST.get('application_amount', '')  # 申请金额
        amount_words = request.POST.get('amount_words', '')  # 金额大写
        funding_source = request.POST.get('funding_source', '')  # 经费来源
        topics_obj = Topics.objects.get(id=int(id))

        if topics_obj.state not in ('refuse', 'draft') and request.user.username != 'admin':
            returnData = {'code': 500, 'message': '修改错误，只有为拒绝状态的议题才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        try:
            # if type_s:
            #     topics_obj.type = type_s
            if ysje_str:
                topics_obj.ysje = ysje_str
            if jfly_str:
                topics_obj.jfly = jfly_str
            if topics_name:
                topics_obj.topics_name = topics_name
            if topics_estimate:
                topics_obj.topics_estimate = topics_estimate
            if contract_type_select:
                topics_obj.contract_type_select = contract_type_select

            if PgCount:
                if topics_text:
                    topics_obj.db_topics_text = base64.b64encode(topics_text.encode("utf-8")).decode(),
                if topics_basis:
                    topics_obj.db_topics_basis = base64.b64encode(topics_basis.encode("utf-8")).decode(),
                if solution:
                    topics_obj.db_solution = base64.b64encode(solution.encode("utf-8")).decode(),
                if nr_wenben:
                    topics_obj.db_nrwb = nr_wenben
                if yj_wenben:
                    topics_obj.db_zcwb = yj_wenben
                if fa_wenben:
                    topics_obj.db_fawb = fa_wenben
                if application_amount:
                    topics_obj.application_amount = application_amount
                if amount_words:
                    topics_obj.amount_words = amount_words
                if funding_source:
                    topics_obj.funding_source = funding_source
                if not adminxiugai:
                    topics_obj.topicsauditrecord_set.filter(state='unaudit').delete()
                    if topics_obj.employee.company.abbreviation in ['YWK', 'DZB', 'YZB', 'SJK']:
                        fg_people_obj = User.objects.get(id=int(fg_people))
                        current_audit_user = fg_people_obj.real_name
                    else:
                        fg_people_obj = topics_obj.employee.company.leaders_id
                        current_audit_user = fg_people_obj.real_name
                    TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=fg_people_obj, audit_note='', state='unaudit', node='db_one_step')
                    TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Company.objects.get(id=3).head_people, audit_note='', state='unaudit', node='db_two_step')
                    TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Company.objects.get(id=3).leaders_id, audit_note='', state='unaudit', node='db_three_step')
                    TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Staffing.objects.get(station="书记").post_personnel.all().first(), audit_note='', state='unaudit', node='sj')

                    topics_obj.state = 'db_one_step'
                    topics_obj.current_audit_user = current_audit_user
                    topics_obj.save()

            else:
                if topics_text:
                    topics_obj.topics_text = base64.b64encode(topics_text.encode("utf-8")).decode(),
                if topics_basis:
                    topics_obj.topics_basis = base64.b64encode(topics_basis.encode("utf-8")).decode(),
                if solution:
                    topics_obj.solution = base64.b64encode(solution.encode("utf-8")).decode(),
                if nr_wenben:
                    topics_obj.nrwb = nr_wenben
                if yj_wenben:
                    topics_obj.zcwb = yj_wenben
                if fa_wenben:
                    topics_obj.fawb = fa_wenben
                if topic_type:
                    topics_obj.topic_type = topic_type
                if pay_type:
                    topics_obj.pay_type = pay_type
                if whether_outweigh:
                    topics_obj.whether_outweigh = whether_outweigh
                if Payee:
                    topics_obj.Payee = Payee
                if receiving_account:
                    topics_obj.receiving_account = receiving_account
                if opening_bank:
                    topics_obj.opening_bank = opening_bank
                if application_amount:
                    topics_obj.application_amount = application_amount
                if amount_words:
                    topics_obj.amount_words = amount_words
                if funding_source:
                    topics_obj.funding_source = funding_source
                if not adminxiugai:
                    if topics_obj.employee.company.abbreviation in ['YWK', 'DZB', 'YZB', 'SJK']:
                        fg_people_obj = User.objects.get(id=int(fg_people))
                        current_audit_user = fg_people_obj.real_name
                    else:
                        fg_people_obj = topics_obj.employee.company.leaders_id
                        current_audit_user = fg_people_obj.real_name

                    if len(topics_obj.topicsauditrecord_set.filter(node='B', state='unaudit')) == 0:
                        TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=fg_people_obj, audit_note='', state='unaudit', node='B')

                    if topics_obj.type == 'yb':
                        if len(topics_obj.topicsauditrecord_set.filter(node='OPR', state='unaudit')) == 0:
                            TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=User.objects.get(job_number="9770"), audit_note='', state='unaudit', node='OPR')

                    if len(topics_obj.topicsauditrecord_set.filter(node='YB/DB', state='unaudit')) == 0:
                        if topics_obj.type == 'db':
                            dbzr = Company.objects.get(id=3).head_people
                        else:
                            dbzr = Company.objects.get(id=80).head_people
                        TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=dbzr, audit_note='', state='unaudit', node='YB/DB')

                    if topics_obj.topicsauditrecord_set.filter(node='Y_D_leader'):
                        if len(topics_obj.topicsauditrecord_set.filter(node='Y_D_leader', state='unaudit')) == 0:
                            if type_s == 'yb':
                                db_leaders = Company.objects.get(id=80).leaders_id
                            else:
                                db_leaders = Company.objects.get(id=3).leaders_id
                            TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=db_leaders, audit_note='', state='unaudit', node='Y_D_leader')

                    if len(topics_obj.topicsauditrecord_set.filter(node='YZ/SJ', state='unaudit')) == 0:
                        if topics_obj.type == 'db':
                            TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Staffing.objects.get(station="书记").post_personnel.all().first(), audit_note='', state='unaudit', node='YZ/SJ')
                        else:
                            TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), audit_note='', state='unaudit', node='YZ/SJ')

                    if topics_obj.topicsauditrecord_set.filter(node='db_leader'):
                        if len(topics_obj.topicsauditrecord_set.filter(node='db_leader', state='unaudit')) == 0:
                            db_leader = topics_obj.employee.company.leaders_id
                            TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=db_leader, audit_note='', state='unaudit', node='db_leader')

                    if topics_obj.topicsauditrecord_set.filter(node='sj'):
                        if len(topics_obj.topicsauditrecord_set.filter(node='sj', state='unaudit')) == 0:
                            TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Staffing.objects.get(station="书记").post_personnel.all().first(), audit_note='', state='unaudit', node='sj')

                    topics_obj.state = 'draft'
                    topics_obj.current_audit_user = current_audit_user
                    topics_obj.save()

            if help_department:
                help_department = json.loads(help_department)
                topics_obj.help_department.clear()
                for company_id in help_department:
                    com = Company.objects.get(id=int(company_id.replace("(", "").replace(")", "")))
                    topics_obj.help_department.add(com)

            if request.user.username == 'admin':
                topics_obj.save()
                returnDict = {'code': 200, 'message': '修改成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            returnDict = {'code': 200, 'message': '修改成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        except Exception as e:
            print("e: ", e)
            topics_obj.state = 'refuse'
            topics_obj.save()
            returnData = {'code': 500, 'message': '修改错误'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class PrintTopicsView(View):
    def get(self, request):
        id = request.GET.get('id', None)
        topics_obj = Topics.objects.get(id=int(id))
        audit_dic = {}
        for audit_obj in topics_obj.topicsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.get_state_display(),
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state': audit_obj.get_state_display(),
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        data_dic = {'apply_user': topics_obj.employee.real_name,
                    'department': topics_obj.employee.department,
                    'state': topics_obj.get_state_display(),
                    'is_yb': topics_obj.is_yb,
                    'topics_name': topics_obj.topics_name,
                    'number': topics_obj.number,
                    'topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(
                        topics_obj.topics_text).decode()).decode()),
                    'topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(
                        topics_obj.topics_basis).decode()).decode()),
                    'solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(
                        topics_obj.solution).decode()).decode()) if topics_obj.type != 'xz' else '',
                    'topics_estimate': topics_obj.topics_estimate,
                    'help_department': ', '.join([item.name for item in topics_obj.help_department.all()]),
                    'jfly': topics_obj.jfly,
                    'ysje': topics_obj.ysje,
                    'uuid': topics_obj.uuid,
                    'audit_list': audit_dic,
                    'title': [['党委会议题审批表', '院长办公会议题审批表'][topics_obj.type == 'yb'], '行政例会议题审批表'][topics_obj.type == 'xz']
                    }

        return render(request, 'personal_center/print_topics.html',
                      {"obj": data_dic})


# 议题列表
class TopicsApplyListView(View):
    def post(self, request):
        page = request.POST.get("page", None)
        topics_obj = Topics.objects.filter(employee_id=request.user.id).order_by("-create_time")
        returnList = []
        for i in topics_obj:
            if i.state == "draft":
                status = "审核中"
            elif i.state == "confirm":
                status = "审核中"
            elif i.state == "audit":
                if "JYDB" in i.number:
                    status = "审核中"
                else:
                    status = "审核中"
            elif i.state == "refuse":
                status = "退回"
            elif i.state == "cancel":
                status = "作废"
            elif i.state == "stop":
                status = "终止"
            else:
                status = "完结"

            one_dict = {"id": i.id, "number": i.number, "status": status, "topics_name": i.topics_name,
                        "create_time": str(i.create_time).split('.')[0][:-3], "spr": i.current_audit_user, 'state': i.state}
            returnList.append(one_dict)
        returnData = {'code': 200, 'message': '', "data": returnList[(int(page) - 1) * 20:int(page) * 20], "count": len(returnList)}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class TopicsApplyCancelView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = Topics.objects.get(id=int(id))
        if state == 'recall':
            obj.current_audit_user = ''
            obj.state = 'recall'
            obj.save()
            temp_list = obj.number.split('-')[0:2]
            temp_number = '-'.join(temp_list)
            sequence_obj = Sequence.objects.filter(type=temp_number)
            obj_sequence = int(obj.number.split('-')[3])
            topice_objs = Topics.objects.filter(create_time__gt=obj.create_time, number__contains=temp_number)
            for topice_obj in topice_objs:
                if int(topice_obj.number.split('-')[3]) > obj_sequence:
                    temp_sequence = int(topice_obj.number.split('-')[3]) - 1
                    topice_obj.number = temp_number + '-' + str(datetime.datetime.now().year) + '-' + str(temp_sequence).zfill(2)
                    topice_obj.save()
            if sequence_obj:
                sequence_obj = sequence_obj.first()
                sequence_obj.sequence -= 1
                sequence_obj.next_sequence -= 1
                sequence_obj.save()
        elif state == 'cancel':
            if obj.state != 'done':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的议题才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_user = ''
                obj.state = 'cancel'
                obj.save()
        elif state == 'stop':
            if obj.state == 'done':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的议题不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_user = ''
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class TopicsApplyBackView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)
        audit_people = request.POST.get('audit_people', None)
        obj = Topics.objects.get(id=int(id))
        audit_people = re.findall('\((.*?)\)', audit_people)
        audit_people_objs = User.objects.filter(job_number__in=audit_people)
        if audit_people_objs.count() > 1:
            returnData = {'code': 500, 'message': '该节点审批人为一人！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        if obj.state in ('cancel', 'refuse'):
            returnData = {'code': 500, 'message': '已经作废或拒绝的流程，不能退回！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            if state == 'draft':
                obj.current_audit_user = obj.topicsauditrecord_set.filter(node='B').first().audit_people.real_name
                audit_objs = obj.topicsauditrecord_set.all()
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            elif state == 'OPR':
                if obj.state == 'draft':
                    returnData = {'code': 500, 'message': '该流程只能退回！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                obj.current_audit_user = obj.topicsauditrecord_set.filter(node='OPR').first().audit_people.real_name
                audit_objs = obj.topicsauditrecord_set.filter(node__in=['OPR', 'yb_result', 'YB/DB', 'YZ/SJ'])
                for audit_obj in audit_objs:
                    if audit_obj.node == 'yb_result':
                        audit_obj.delete()
                    else:
                        audit_obj.audit_note = ''
                        audit_obj.state = 'unaudit'
                        audit_obj.save()

                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            elif state == 'audit':
                if obj.state in ['draft', 'yd_leader', 'confirm']:
                    returnData = {'code': 500, 'message': '该流程只能退回！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                obj.current_audit_user = obj.topicsauditrecord_set.filter(node='YZ/SJ').first().audit_people.real_name
                audit_objs = obj.topicsauditrecord_set.filter(node__in=['YZ/SJ', 'yb_result', 'db_result'])
                for audit_obj in audit_objs:
                    if audit_obj.node == 'YZ/SJ':
                        audit_obj.audit_note = ''
                        audit_obj.state = 'unaudit'
                        audit_obj.save()
                    else:
                        audit_obj.delete()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'confirm':
                if obj.state == 'draft':
                    returnData = {'code': 500, 'message': '该流程只能退回！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

                obj.current_audit_user = obj.topicsauditrecord_set.filter(node='YB/DB').first().audit_people.real_name
                audit_objs = obj.topicsauditrecord_set.filter(node__in=['YB/DB', 'yd_leader', 'YZ/SJ', 'yb_result', 'db_result'])
                for audit_obj in audit_objs:
                    if audit_obj.node in ['yb_result', 'db_result']:
                        audit_obj.delete()
                    else:
                        audit_obj.audit_note = ''
                        audit_obj.state = 'unaudit'
                        audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            elif state == 'yd_leader':
                if obj.state in ['draft', 'confirm']:
                    returnData = {'code': 500, 'message': '该流程只能退回！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                if obj.topicsauditrecord_set.filter(node='yd_leader'):
                    obj.current_audit_user = obj.topicsauditrecord_set.filter(node='yd_leader').first().audit_people.real_name
                    audit_objs = obj.topicsauditrecord_set.filter(node__in=['yd_leader', 'YZ/SJ', 'yb_result', 'db_result'])
                    for audit_obj in audit_objs:
                        if audit_obj.node in ['yb_result', 'db_result']:
                            audit_obj.delete()
                        else:
                            audit_obj.audit_note = ''
                            audit_obj.state = 'unaudit'
                            audit_obj.save()
                else:
                    returnData = {'code': 500, 'message': '该流程为新系统上线之前流程，无党政办分管领导审核！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'refuse':
                audit_objs = obj.topicsauditrecord_set.all()
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.current_audit_user = obj.employee.real_name
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'unmetting':
                obj.state = 'unmetting'
                obj.meetings_num = '0'
                obj.is_meeting = 'a'
                TopMeetObj = obj.topic_meeting_set.all().first()
                TopMeetObj.voteleader_set.all().delete()
                TopMeetObj.delete()
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'metting':
                obj.state = 'metting'
                obj.is_audit = True
                if obj.type == 'yb':
                    obj.topicsauditrecord_set.filter(node='yb_result').delete()
                elif obj.type == 'db':
                    obj.topicsauditrecord_set.filter(node='db_result').delete()
                else:
                    obj.topicsauditrecord_set.filter(node='xz_result').delete()

                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                returnData = {'code': 500, 'message': '请选择正确的状态！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")


class TopicsApplyStopView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = Topics.objects.get(id=int(id))
        if obj.employee != request.user:
            returnData = {'code': 500, 'message': '终止失败！只有申请人才能终止流程'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_user = ''
        obj.state = 'stop'
        obj.save()
        returnData = {'code': 200, 'message': '成功终止！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


# 附件上传
class TopicsAttachmentsView(View):
    def post(self, request):
        file2 = request.FILES.get('file2')  # 附件
        number = request.POST.get('number', 'zzzzz')  # 编号
        source = request.POST.get('source', None)  # 来源 公文 gw 议题 yt  上级来文 lw 用印申请 yysq  资产管理  zc 通知公告 tz
        file1 = request.FILES.get('file1')  # 正文
        bill_id = request.POST.get('bill_id', '')  # 单据id
        voucher = request.POST.get('voucher', '')  # 凭证
        admin_flag = request.POST.get('admin', '')
        job_number = request.POST.get('job_number', '')
        contract = request.POST.get('contract', '')

        try:
            if request.user.real_name == '管理员':
                users = Topicsattachments.objects.filter(topics_number=number).first().uploader_user
            else:
                users = request.user
        except:
            users = request.user
        if not source:
            returnDict = {'code': 500, 'message': '请传来源！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        FileType = '0' if file1 else '1'
        file1 = file1 if file1 else file2
        print("=======================", file1)
        if file1:
            topics_file_obj = Topicsattachments.objects.create(
                topics_number=number,
                file_path=file1,
                file_size=public_file.StrOfSize(file1.size),
                uploader=request.user.username,
                file_type=FileType,
                is_deleted=False,
                source=source,
                uploader_user=users if not job_number else User.objects.get(job_number=job_number)
            )
            print("=======================", topics_file_obj.id)
            if admin_flag:
                if FileType == '0':
                    xiugai_obj = Topicsattachments.objects.filter(topics_number=number, file_type='0')

                else:
                    xiugai_obj = Topicsattachments.objects.filter(topics_number=number, file_type='1')
                    if not xiugai_obj:
                        xiugai_obj = Topicsattachments.objects.filter(topics_number=number)

                if xiugai_obj:
                    topics_file_obj.create_time = xiugai_obj.first().create_time
                    topics_file_obj.update_time = xiugai_obj.first().update_time
                    topics_file_obj.uploader_user = xiugai_obj.first().uploader_user
                    topics_file_obj.uploader = xiugai_obj.first().uploader

            sys_path = os.getcwd()
            file_name = file1.name
            topics_file_obj.file_name = file_name
            topics_file_obj.save()


            word_path = sys_path + '/media/' + str(topics_file_obj.file_path)
            old_word_path = word_path
            temp_name = os.path.splitext(file_name)[0]
            new_word_path = old_word_path.replace(os.path.splitext(topics_file_obj.file_path.name.split("/")[-1])[0], temp_name)
            os.rename(old_word_path, new_word_path)
            word_path = new_word_path

            file_path = topics_file_obj.file_path.name.replace(os.path.splitext(topics_file_obj.file_path.name.split("/")[-1])[0], temp_name)

            pdf_path = word_path
            if word_path.split('.')[-1] in ['docx', 'doc', 'DOC', 'DOCX']:
                pdf_path = ParseWord().word2pdf(word_path)
            elif word_path.split(".")[-1] in ['ppt', 'pptx']:
                pdf_path = ParseWord().ppt2pdf(word_path)
            elif word_path.split(".")[-1] in ['xls', 'xlsx', 'XLS', 'XLSX'] and source != "rspb":
                b = xlrd.open_workbook(word_path)
                sheetnum = len(b.sheets())
                pdfConverter = PDFConverter(word_path, sheetnum, os.path.splitext(file_name)[0])
                pdf_path = pdfConverter.run_conver()
            else:
                pdf_path = '/media/' + str(file_path)
            pdf_list = []
            if type(pdf_path) is list:
                for i in range(len(pdf_path)):
                    if i == 0:
                        topics_file_obj.pdf_path = pdf_path[i].replace(os.getcwd(), '')
                        tic_id = topics_file_obj.id
                        topics_file_obj.save()
                    else:
                        all_file = Topicsattachments.objects.create(
                            topics_number=number,
                            file_path=file1,
                            file_size=public_file.StrOfSize(file1.size),
                            uploader=request.user.username,
                            file_type=FileType,
                            pdf_path=pdf_path[i].replace(os.getcwd(), ''),
                            file_name=os.path.split(pdf_path[i])[1],
                            source=source,
                            uploader_user=users if not job_number else User.objects.get(job_number=job_number)
                        )
                        tic_id = all_file.id
                        if request.user.username == 'admin' and bill_id:
                            if source == 'lw':
                                bill_obj = OfficialDocuments.objects.get(id=bill_id)
                                Topicsattachments.objects.filter(id=all_file.id).update(
                                    uploader_user=bill_obj.apply_user,
                                    create_time=bill_obj.create_time)
                            if source == 'yt':
                                bill_obj = Topics.objects.get(id=bill_id)
                                Topicsattachments.objects.filter(id=all_file.id).update(
                                    uploader_user=bill_obj.employee,
                                    create_time=bill_obj.create_time)
                            if source == 'gw':
                                bill_obj = ConferenceMemo.objects.get(id=bill_id)
                                Topicsattachments.objects.filter(id=all_file.id).update(
                                    uploader_user=bill_obj.apply_user, create_time=bill_obj.create_time)

                    one_dict = {"id": tic_id, 'pdf_path': pdf_path[i].replace(os.getcwd(), '')}
                    pdf_list.append(one_dict)
                pdf_path = pdf_list

            else:
                old_path = pdf_path
                fileName = pdf_path.split("/")[-1].split(".")[0]
                pdf_path = pdf_path.replace(fileName, file1.name.split(".")[0]).replace(os.getcwd(), "")
                # os.rename(os.getcwd() + old_path, os.getcwd() + pdf_path)
                pdf_path = pdf_path.replace(os.path.splitext(os.path.split(pdf_path)[1])[0], os.path.splitext(file_name)[0])
                topics_file_obj.pdf_path = pdf_path
                topics_file_obj.save()
            sql = ''' update administrative_topicsattachments set file_path = %(file_path)s where id = %(id)s '''
            with connection.cursor() as cursor:
                cursor.execute(sql, {'file_path': file_path, 'id': topics_file_obj.id})
            if request.user.username == 'admin' and bill_id:
                if source == 'lw':
                    bill_obj = OfficialDocuments.objects.get(id=bill_id)
                    Topicsattachments.objects.filter(id=topics_file_obj.id).update(uploader_user=bill_obj.apply_user)
                if source == 'yt':
                    bill_obj = Topics.objects.get(id=bill_id)
                    Topicsattachments.objects.filter(id=topics_file_obj.id).update(uploader_user=bill_obj.employee)
                if source == 'gw':
                    bill_obj = ConferenceMemo.objects.get(id=bill_id)
                    Topicsattachments.objects.filter(id=topics_file_obj.id).update(uploader_user=bill_obj.apply_user)
            topics_file_obj = Topicsattachments.objects.get(id=topics_file_obj.id)
            returnDict = {'code': 200, 'message': '获取成功', 'file_name': file_name, 'id': topics_file_obj.id, "file_type": FileType,
                          'file_size': topics_file_obj.file_size, 'uploader': topics_file_obj.uploader_user.real_name, "pdf_path": pdf_path,
                          'upload_time': topics_file_obj.create_time.strftime("%Y-%m-%d %H:%M")}
            if voucher:
                SealObj = SealApply.objects.get(fj_number=number)
                SealObj.voucher = "1"
                SealObj.save()
            if contract:
                topics_file_obj.file_type = '3'
                topics_file_obj.save()
                if source == 'jjhthq':
                    ContractObj = ContractApproval.objects.get(fj_number=number)
                    ContractObj.whether_upload = '1'
                    ContractObj.current_audit_users.clear()
                    ContractObj.state = 'end'
                    ContractObj.save()
                else:
                    SealObj = SealApply.objects.get(fj_number=number)
                    SealObj.whether_upload = '1'
                    SealObj.save()
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        else:
            returnDict = {'code': 500, 'message': '取消上传！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

class DeleteAttachmentsView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        if id:
            obj = Topicsattachments.objects.filter(id=id).first()
            if obj:
                obj.delete()
            returnDict = {'code': 200, 'message': '删除成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            returnDict = {'code': 500, 'message': '删除失败'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PersonalAttachmentsView(View):
    def post(self, request):
        file = request.FILES.get('file')
        is_secrecy = request.POST.get('is_secrecy', None)  # 'true' 'false'
        watched_users = request.POST.get('watched_users', None)  # 孔智慧(8166)
        if file:
            topics_file_obj = PersonalAttachments.objects.create(
                file_path=file,
                is_secrecy=True if is_secrecy == 'true' else False,
                file_size=public_file.StrOfSize(file.size),
                uploader_user=request.user
            )
            if watched_users:
                watched_users = re.findall('\((.*?)\)', watched_users)
                watched_user_objs = User.objects.filter(job_number__in=watched_users)
                for watched_user_obj in watched_user_objs:
                    topics_file_obj.watched_users.add(watched_user_obj)

            sys_path = os.getcwd()
            file_name = file.name
            topics_file_obj.file_name = file_name
            topics_file_obj.save()
            word_path = sys_path + '/media/' + str(topics_file_obj.file_path)
            old_word_path = word_path
            temp_name = os.path.splitext(file_name)[0]
            new_word_path = old_word_path.replace(os.path.splitext(topics_file_obj.file_path.name.split("/")[-1])[0],
                                                  temp_name)

            os.rename(old_word_path, new_word_path)
            word_path = new_word_path
            file_path = topics_file_obj.file_path.name.replace(
                os.path.splitext(topics_file_obj.file_path.name.split("/")[-1])[0], temp_name)
            if word_path.split('.')[-1] in ['docx', 'doc']:
                pdf_path = ParseWord().word2pdf(word_path)
            elif word_path.split(".")[-1] in ['ppt', 'pptx']:
                pdf_path = ParseWord().ppt2pdf(word_path)
            else:
                pdf_path = '/media/' + str(file_path)
            topics_file_obj.pdf_path = pdf_path
            topics_file_obj.save()
            sql = ''' update administrative_personalattachments set file_path = %(file_path)s where id = %(id)s '''
            with connection.cursor() as cursor:
                cursor.execute(sql, {'file_path': file_path, 'id': topics_file_obj.id})
            returnDict = {'code': 200, 'message': '获取成功', 'file_name': file_name, 'id': topics_file_obj.id,
                          'file_size': topics_file_obj.file_size, 'uploader': request.user.real_name, "pdf_path": pdf_path,
                          'upload_time': topics_file_obj.create_time.strftime("%Y-%m-%d %H:%M")}

            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class DeletePersonalAttachmentsView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        if id:
            obj = PersonalAttachments.objects.filter(id=id).first()
            if obj:
                sys_path = os.getcwd()
                if os.path.exists(os.path.join(sys_path, obj.file_path.name)):
                    os.remove(os.path.join(sys_path, obj.file_path.name))
                if os.path.exists(os.path.join(sys_path, obj.pdf_path)):
                    os.remove(os.path.join(sys_path, obj.file_path.name))
                obj.delete()
            returnDict = {'code': 200, 'message': '删除成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            returnDict = {'code': 500, 'message': '删除失败'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


def get_state_to_node(state, type):
    if state == 'one':
        return '核稿'
    elif state == 'two':
        return '复核'
    elif state == 'three' and type in ('a', 'b', 'c', 'd'):
        return '会签'
    elif state == 'three' and type not in ('a', 'b', 'c', 'd'):
        return '签发'
    elif state == 'four':
        return '会签'
    else:
        return '结束'


class ConferenceMemoListView(View):
    def get(self, request):
        page = request.GET.get("page", 1)
        cunt_type = request.GET.get("cunt_type", "0")
        user = request.user
        audit_objs = user.conference_memo_users.all().order_by("-create_time")
        already_audit_objs = user.conference_memo_already_audit_users.all().order_by("-create_time")
        my_apply_objs = user.conferencememo_set.all().order_by("-create_time")
        my_apply_list = [{'id': audit_obj.id, 'type': audit_obj.type, 'document_number': audit_obj.document_number,
                          'state': audit_obj.state,
                          'title': audit_obj.conference_memo_text,
                          'is_cancel': str(audit_obj.conferencememoauditrecord_set.filter(
                              Q(state='draft') | Q(state='audit')).count()),
                          'create_time': str(audit_obj.create_time).split('.')[0][:-3],
                          'apply_user': audit_obj.apply_user.real_name, 'department': audit_obj.apply_user.department,
                          'audit_user': ' ,'.join([i.real_name for i in audit_obj.current_audit_users.all()])}
                         for
                         audit_obj in my_apply_objs[(int(page) - 1) * 20:int(page) * 20]]
        audit_list = [{'id': audit_obj.id, 'type': audit_obj.type, 'document_number': audit_obj.document_number,
                       'state': audit_obj.state,
                       'title': audit_obj.conference_memo_text,
                       'create_time': str(audit_obj.create_time).split('.')[0][:-3],
                       'apply_user': audit_obj.apply_user.real_name, 'department': audit_obj.apply_user.department,
                       'audit_user': ' ,'.join([i.real_name for i in audit_obj.current_audit_users.all()])}
                      for
                      audit_obj in audit_objs[(int(page) - 1) * 20:int(page) * 20]]
        already_audit_list = [{'id': audit_obj.id, 'type': audit_obj.type, 'document_number': audit_obj.document_number,
                               'state': audit_obj.state,
                               'title': audit_obj.conference_memo_text,
                               'create_time': str(audit_obj.create_time).split('.')[0][:-3],
                               'apply_user': audit_obj.apply_user.real_name,
                               'department': audit_obj.apply_user.department,
                               'audit_user': ' ,'.join([i.real_name for i in audit_obj.current_audit_users.all()])} for
                              audit_obj in already_audit_objs[(int(page) - 1) * 20:int(page) * 20]]
        if cunt_type == '0':            # 查询全部
            returnData = {'code': 200, 'message': '获取成功！', 'audit_list': audit_list,
                          'already_audit_list': already_audit_list,
                      'my_apply_list': my_apply_list, "my_apply_list_len": my_apply_objs.count(),
                      "already_audit_list_len": already_audit_objs.count(), 'audit_len': audit_objs.count()}
        elif cunt_type == '1':          # 查询我的申请
            returnData = {'code': 200, 'message': '获取成功！', 'my_apply_list': my_apply_list, "my_apply_list_len": my_apply_objs.count()}

        elif cunt_type == '2':          # 查询我的待办
            returnData = {'code': 200, 'message': '获取成功！', 'audit_list': audit_list, "audit_len": audit_objs.count()}

        else:                           # 查询我的已办
            returnData = {'code': 200, 'message': '获取成功！', 'already_audit_list': already_audit_list, "already_audit_list_len": already_audit_objs.count()}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ConferenceMemoIndexView(View):
    def get(self, request):
        user = request.user
        page = request.GET.get("page", 1)
        accept_objs = user.conferencememopeople_set.filter(state='accept').order_by("-create_time")
        accepted_objs = user.conferencememopeople_set.filter(state='accepted').order_by("-create_time")
        accept_list = [{'id': record.notice_id.id, 'type': record.notice_id.type,
                        'document_number': record.notice_id.document_number,
                        'state': get_state_to_node(record.notice_id.state, record.notice_id.type),
                        'title': record.notice_id.conference_memo_text,
                        'create_time': str(record.notice_id.create_time).split('.')[0][:-3],
                        'apply_user': record.notice_id.apply_user.real_name,
                        'department': record.notice_id.apply_user.department} for
                       record in
                       accept_objs]
        accepted_list = [{'id': record.notice_id.id, 'type': record.notice_id.type,
                          'document_number': record.notice_id.document_number,
                          'state': get_state_to_node(record.notice_id.state, record.notice_id.type),
                          'title': record.notice_id.conference_memo_text,
                          'create_time': str(record.notice_id.create_time).split('.')[0][:-3],
                          'apply_user': record.notice_id.apply_user.real_name,
                          'department': record.notice_id.apply_user.department} for
                         record in
                         accepted_objs[
                         (int(page) - 1) * 20:int(page) * 20]]

        returnData = {'code': 200, 'message': '获取成功！', 'accept_list': accept_list, 'accepted_list': accepted_list,
                      'len_accepted_list': accepted_objs.count()}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        document_number = request.POST.get('document_number', None)
        number = request.POST.get('number', None)
        type = request.POST.get('type', None)  # 类型
        main_company = request.POST.get('main_company', '')
        vice_company = request.POST.get('vice_company', '')
        servings = request.POST.get('servings', '')  # 分数
        conference_memo_text = request.POST.get('conference_memo_text', None)  # 事由
        fg_people = request.POST.get('fg_people', None)  # 分管领导
        drafter = request.POST.get('drafter', None)  # 拟稿人
        qf_people = request.POST.get('qf_people', None)  # 签发人
        drafter_company = request.POST.get('drafter_company', None)  # 拟稿人部门
        gist = request.POST.get('gist', '')
        leaders_id_str = request.POST.get('leaders_id_str', '')
        try:
            if not id:
                conference_memo_obj = ConferenceMemo.objects.create(apply_user=request.user, type=type, servings=servings,
                                                                    conference_memo_text=conference_memo_text,
                                                                    document_number=document_number, number=number, document_year=datetime.datetime.now().strftime("%Y"),
                                                                    main_company=main_company, vice_company=vice_company, gist=gist)
            else:
                conference_memo_obj = ConferenceMemo.objects.get(id=int(id))
                conference_memo_obj.conference_memo_text = conference_memo_text
                conference_memo_obj.main_company = main_company
                conference_memo_obj.vice_company = vice_company
                conference_memo_obj.gist = gist
                conference_memo_obj.state = 'one'
                conference_memo_obj.save()
            if fg_people:
                conference_memo_obj.fg_people_id = int(fg_people)
            if qf_people:
                conference_memo_obj.qf_people_id = int(qf_people)
            conference_memo_obj.save()
            sequence_obj = Sequence.objects.filter(type=conference_memo_obj.type).first()
            if sequence_obj:
                sequence_obj.sequence += 1
                sequence_obj.next_sequence += 1
                sequence_obj.save()
            dbzr = Company.objects.get(id=3).head_people
            conference_memo_obj.current_audit_users.add(dbzr)
        except Exception as e:
            print(e)
            returnDict = {'code': 500, 'message': '创建错误！请联系管理员！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            conference_memo_obj.drafter = drafter
            conference_memo_obj.drafter_company = drafter_company
            conference_memo_obj.save()
            com_objs = Company.objects.filter(name=drafter_company)
            if conference_memo_obj.type in ('a', 'g', 'c', 'i'):
                print("============", "党委")
                if conference_memo_obj.type in ('f', 'g', 'h'):
                    conference_memo_obj.state = 'nine'
                    conference_memo_obj.save()
                    conference_memo_obj.current_audit_users.remove(dbzr)
                    com_obj = com_objs.first()
                    if com_obj.head_people:
                        user = com_obj.head_people
                    else:
                        achments_objs = Topicsattachments.objects.filter(topics_number=conference_memo_obj.number)
                        if achments_objs.count() > 0:
                            achments_objs.delete()
                        conference_memo_obj.delete()
                        sequence_obj.sequence -= 1
                        sequence_obj.next_sequence -= 1
                        sequence_obj.save()
                        returnDict = {'code': 500, 'message': '创建错误, 拟稿部门未找到负责人！'}
                        return HttpResponse(json.dumps(returnDict), content_type="application/json")
                    if com_obj.id in [3, 80]:
                        nine_people = Staffing.objects.get(station="党委办公室").post_personnel.all()
                        for ni_pe in nine_people:
                            ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=ni_pe, audit_note='', node='C/D')
                            conference_memo_obj.current_audit_users.add(ni_pe)
                    else:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=user, audit_note='', node='C/D')
                        conference_memo_obj.current_audit_users.add(user)
                    if conference_memo_obj.type == "g":
                        pass
                        # prg_people = Staffing.objects.get(station="党委办公室").post_personnel.all()
                        # for Prg in prg_people:
                        #     ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=Prg, audit_note='', node='PRG')
                    else:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=request.user, audit_note='', node='PRG')
                ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=dbzr, audit_note='', node='YB/DB')
                if type in ('a', 'c'):
                    dzb_leader = Company.objects.get(id=3).leaders_id
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=dzb_leader, audit_note='', node='YBL/DBL')
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=Staffing.objects.get(station="书记").post_personnel.all().first(), audit_note='', node='YZ/SJ')
                elif type in ('b', 'd', 'e'):
                    if type not in ['b', 'd']:
                        yzb_leader = Company.objects.get(id=80).leaders_id
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=yzb_leader, audit_note='', node='YBL/DBL')
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), audit_note='', node='YZ/SJ')
                else:
                    if fg_people:
                        if request.user.company.id != 80:
                            fg_people_obj = User.objects.get(id=int(fg_people))
                            ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=fg_people_obj, audit_note='', node='YBL/DBL')
                        else:
                            com_obj = com_objs.first()
                            if com_obj.id not in [3, 80]:
                                fg_people_obj = User.objects.get(id=int(fg_people))
                                ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=fg_people_obj, audit_note='', node='YBL/DBL')
                    else:
                        returnDict = {'code': 500, 'message': '请传分管领导！'}
                        return HttpResponse(json.dumps(returnDict), content_type="application/json")
                    if type in ['g', 'i']:
                        if type == 'g':
                            BGS_appave = Staffing.objects.get(station='党委印章管理员').post_personnel.all().first()
                            ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=BGS_appave, audit_note='', node='BGS')
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=Staffing.objects.get(station="书记").post_personnel.all().first(),
                                                                 audit_note='', node='YZ/SJ')
                    else:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people_id=int(qf_people), audit_note='', node='YZ/SJ')

                        BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=BGS_appave, audit_note='', node='BGS')

            else:
                print("============", "院办", conference_memo_obj.type )
                dean_obj = Staffing.objects.get(station="院长").post_personnel.all().first()
                conference_memo_obj.current_audit_users.remove(dbzr)
                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                one_step = Company.objects.get(id=80).head_people
                if conference_memo_obj.type in ['b', 'd']:
                    flag = False
                    if request.user != one_step:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=one_step, audit_note='', node='YB/DB')
                        conference_memo_obj.state = "one"
                        conference_memo_obj.current_audit_users.add(one_step)
                        flag = True
                    else:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=one_step, audit_note='', node='YB/DB', state='audit')

                    if conference_memo_obj.type == 'b':
                        years = re.findall("〔(.*?)〕(.*?)号", conference_memo_obj.document_number)[0][0]
                        topic_number = re.findall("〔(.*?)〕(.*?)号", conference_memo_obj.document_number)[0][1]
                        meet_objs = topic_meeting.objects.filter(topic_type='yb', topic_year=years, meet_number=topic_number).first().voteleader_set.filter(vote=True)
                        for hhh in meet_objs:
                            if hhh.leaders != dean_obj:
                                ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=hhh.leaders, audit_note='', node='B')
                                if not flag:
                                    conference_memo_obj.current_audit_users.add(hhh.leaders)
                                    conference_memo_obj.state = "four"
                    else:
                        leaders_id_list = leaders_id_str.split(",")
                        for hhhh in leaders_id_list:
                            if hhhh.strip():
                                countersign_obj = User.objects.get(id=int(hhhh.strip()))
                                ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=countersign_obj, audit_note='', node='B')
                                if not flag:
                                    conference_memo_obj.current_audit_users.add(countersign_obj)
                                    conference_memo_obj.state = "four"
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), audit_note='', node='YZ/SJ')

                elif conference_memo_obj.type in ['h', 'f']:
                    conference_memo_obj.state = 'nine'
                    com_obj = com_objs.first()
                    draft_people  = com_obj.head_people
                    if com_obj.id in [3, 80]:
                        nine_people = Staffing.objects.get(station="医院办公室").post_personnel.all()
                        for ni_pe in nine_people:
                            ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=ni_pe, audit_note='', node='C/D')
                            conference_memo_obj.current_audit_users.add(ni_pe)
                    else:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=draft_people, audit_note='', node='C/D')
                        conference_memo_obj.current_audit_users.add(draft_people)
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=one_step, audit_note='', node='YB/DB')
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), audit_note='', node='YZ/SJ')
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=BGS_appave, audit_note='', node='BGS')

                else:
                    flag = False
                    if request.user != one_step:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=one_step, audit_note='', node='YB/DB')
                        conference_memo_obj.state = "one"
                        conference_memo_obj.current_audit_users.add(one_step)
                        flag = True
                    else:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=one_step, audit_note='', node='YB/DB', state='audit')
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), audit_note='', node='YZ/SJ')
                    if not flag:
                        conference_memo_obj.state = "five"
                        conference_memo_obj.current_audit_users.add(Staffing.objects.get(station="院长").post_personnel.all().first())

            conference_memo_obj.save()
            topic_type = "公文审批"
            applicant = conference_memo_obj.apply_user.real_name
            ApplicationTime = conference_memo_obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = conference_memo_obj.conference_memo_text[:15] + "……" if len(conference_memo_obj.conference_memo_text) > 15 else conference_memo_obj.conference_memo_text
            try:
                RecordAndPush().MessagePush(conference_memo_obj.current_audit_users.all().first().openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
            returnDict = {'code': 200, 'message': '创建成功！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ConferenceMemoDraftView(View):
    def get(self, request):
        id = request.GET.get('id', None)
        obj = ConferenceMemo.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.number)]
        leaders = User.objects.filter(group_id=2, is_delete=False)
        qf_leaders = User.objects.filter(group_id=1, is_delete=False)
        title = ''
        if obj.type == 'a':
            title = '党委会议纪要'
        if obj.type == 'b':
            title = '院长办公会会议纪要'
        if obj.type == 'c':
            title = '党委专题会议纪要'
        if obj.type == 'd':
            title = '院长办公会专题会议纪要'
        if obj.type == 'g':
            title = '党委公文'
        if obj.type == 'e':
            title = '行政例会简报'
        if obj.type == 'i':
            title = '京医团总支发文'
        if obj.type in ('f', 'h'):
            title = '行政公文'
        company_list = [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]
        sign_jointly = User.objects.filter(group_id__in=[1, 2], is_delete=False)
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list, 'leaders': leaders,
                   'company_list': company_list, 'qf_leaders': qf_leaders, 'title': title, 'tmpe_list1': ['h', 'f'],
                   'tmpe_list2': ['h', 'f', 'g', 'i'], 'sign_jointly': sign_jointly}
        return render(request, 'personal_center/conference_memo_draft.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        document_number = request.POST.get('document_number', None)
        number = request.POST.get('number', None)
        type = request.POST.get('type', None)  # 类型
        main_company = request.POST.get('main_company', '')
        vice_company = request.POST.get('vice_company', '')
        servings = request.POST.get('servings', None)  # 分数
        conference_memo_text = request.POST.get('conference_memo_text', None)  # 事由
        fg_people = request.POST.get('fg_people', None)  # 分管领导
        drafter = request.POST.get('drafter', None)  # 拟稿人
        qf_people = request.POST.get('qf_people', None)  # 签发人
        gist = request.POST.get('gist', '')
        drafter_company = request.POST.get('drafter_company', None)  # 拟稿人部门
        if not id:
            conference_memo_obj = ConferenceMemo.objects.create(apply_user=request.user, type=type,
                                                                servings=int(servings) if servings else "",
                                                                conference_memo_text=conference_memo_text,
                                                                document_number=document_number, number=number,
                                                                document_year=datetime.datetime.now().strftime("%Y"),
                                                                main_company=main_company, vice_company=vice_company,
                                                                drafter=drafter, drafter_company=drafter_company,
                                                                gist=gist,
                                                                state='draft')
        else:
            conference_memo_obj = ConferenceMemo.objects.get(id=int(id))
            conference_memo_obj.conference_memo_text = conference_memo_text
            conference_memo_obj.main_company = main_company
            conference_memo_obj.vice_company = vice_company
            conference_memo_obj.drafter = drafter
            conference_memo_obj.drafter_company = drafter_company
            conference_memo_obj.gist = gist
            conference_memo_obj.save()

        if fg_people:
            conference_memo_obj.fg_people_id = int(fg_people)
        if qf_people:
            conference_memo_obj.qf_people_id = qf_people
        conference_memo_obj.save()
        returnDict = {'code': 200, 'message': '保存成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ConferenceMemoDetailView(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get('id', None)
        receiving = request.GET.get('receiving', None)
        try:
            conference_memo_obj = ConferenceMemo.objects.get(id=id)
            # if request.user in [record.audit_people for record in conference_memo_obj.conferencememopeople_set.all()]:
            p_obj = conference_memo_obj.conferencememopeople_set.filter(audit_people=request.user, state='accept').first()
            if p_obj:
                p_obj.state = 'accepted'
                p_obj.update_time = datetime.datetime.now()
                p_obj.save()

            if receiving == "true":
                file_obj = Topicsattachments.objects.filter(topics_number=conference_memo_obj.number,
                                                            file_type=1) if Topicsattachments.objects.filter(
                    topics_number=conference_memo_obj.number, file_type=1) else Topicsattachments.objects.filter(
                    topics_number=conference_memo_obj.number, file_type=0)
                file_list = [
                    {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                     "file_path": atta_obj.pdf_path.replace("\\", '/'),
                     "pdf_path": atta_obj.pdf_path.replace("\\", '/'),
                     "file_size": atta_obj.file_size,
                     "file_type": atta_obj.file_type,
                     "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                     'word_path': os.getcwd() + "/media/" + str(atta_obj.file_path).replace("\\", '/'),
                     "uploader": atta_obj.uploader_user.real_name, "id": atta_obj.id,
                     "topics_number": atta_obj.topics_number} for atta_obj in file_obj]
            else:
                file_list = [
                    {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                     "file_path": atta_obj.pdf_path.replace("\\", '/'), "pdf_path": atta_obj.pdf_path.replace("\\", '/'),
                     "file_size": atta_obj.file_size, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                     "file_type": atta_obj.file_type,
                     'word_path': os.getcwd() + "/media/" + str(atta_obj.file_path).replace("\\", '/'),
                     "uploader": atta_obj.uploader_user.real_name, "id": atta_obj.id,
                     "topics_number": atta_obj.topics_number} for atta_obj in
                    Topicsattachments.objects.filter(topics_number=conference_memo_obj.number)]

        except Exception as e:
            returnDict = {'code': 500, 'message': '获取错误！请联系管理员！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            # audit_list = []
            audit_dic = {}
            for audit_obj in conference_memo_obj.conferencememoauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.get_state_display(),
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.get_state_display(),
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            recive_people = [{'user': record.real_name, 'state': record.get_state_display(),
                              'signature_picture': '/media/' + str(
                                  record.signature_picture) if (
                                      record.signature_picture and record.state == 'accepted') else '',
                              'update_time': record.update_time.strftime(
                                  "%Y-%m-%d %H:%M") if record.state == 'accepted' else ''}
                             for record in conference_memo_obj.conferencememopeople_set.all()]

            data_dic = {
                'id': conference_memo_obj.id,
                'gist': conference_memo_obj.gist,
                'state': conference_memo_obj.get_state_display(),
                'apply_user': conference_memo_obj.apply_user.real_name if conference_memo_obj.type not in ['h', 'f'] else conference_memo_obj.drafter,
                'department': conference_memo_obj.apply_user.department if conference_memo_obj.type not in ['h', 'f'] else conference_memo_obj.drafter_company,
                'drafter': conference_memo_obj.drafter,
                'drafter_company': conference_memo_obj.drafter_company,
                'servings': conference_memo_obj.servings,
                'file_list': file_list,
                'type': conference_memo_obj.type,
                'conference_memo_text': conference_memo_obj.conference_memo_text,
                'main_company': conference_memo_obj.main_company,
                'vice_company': conference_memo_obj.vice_company,
                'document_number': conference_memo_obj.document_number,
                'number': conference_memo_obj.number,
                'audit_list': audit_dic,
                'recive_people': recive_people,
                'len_recive_people': len(recive_people),
                'is_stop': 'true' if conference_memo_obj.state in ['nine', 'one', 'two', 'three', 'four', 'five', 'eight'] and request.user == conference_memo_obj.apply_user else 'false',        # 中止
                'is_cancel': 'true' if conference_memo_obj.state == 'seven' and request.user == conference_memo_obj.apply_user else 'false',                # 作废
                'is_recall': 'true' if conference_memo_obj.conferencememoauditrecord_set.filter(
                    state__in=['draft', 'audit']).count() == 0 and request.user == conference_memo_obj.apply_user and conference_memo_obj.state not in ['stop', 'recall'] else 'false',                                         # 撤回
            }
            returnDict = {'code': 200, 'message': '获取成功', 'data_dic': data_dic, "receiving": receiving}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过 abstention 弃权
        hq_people = request.POST.get('hq_people', None) # 会签人员
        RecordAndPush().OperationRecords(request, "公文管理")
        if not state:
            returnData = {'code': 500, 'message': '参数错误，请联系管理员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        conference_memo_obj = ConferenceMemo.objects.get(id=id)
        conference_memo_obj.audit_users_already.add(request.user)

        topic_type = "公文审批"
        applicant = conference_memo_obj.apply_user.real_name
        ApplicationTime = conference_memo_obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = conference_memo_obj.conference_memo_text[:15] + "……" if len(conference_memo_obj.conference_memo_text) > 15 else conference_memo_obj.conference_memo_text

        if conference_memo_obj.type in ['a', 'g', 'c', 'i']:
            if conference_memo_obj.state == 'nine':
                if not conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit', audit_people=request.user):
                    returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit', audit_people=request.user).first()
                audit_record_obj.state = state
                audit_record_obj.audit_note = audit_note
                audit_record_obj.update_time = datetime.datetime.now()
                conference_memo_obj.current_audit_users.clear()
                audit_record_obj.save()
                conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit').delete()
                if state == 'audit':
                    if conference_memo_obj.conferencememoauditrecord_set.filter(node='PRG', state='unaudit'):
                        t_state = 'eleven'
                        audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='PRG', state='unaudit')
                        for aaa in audit_record_obj_next:
                            conference_memo_obj.current_audit_users.add(aaa.audit_people)
                    else:
                        t_state = 'one'
                        audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                    try:
                        RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                else:
                    t_state = 'six'
                    conference_memo_obj.current_audit_users.clear()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                conference_memo_obj.state = t_state
                conference_memo_obj.save()

                returnData = {'code': 200, 'message': '操作成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'eleven':
                if not conference_memo_obj.conferencememoauditrecord_set.filter(node='PRG', state='unaudit', audit_people=request.user):
                    returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='PRG', state='unaudit', audit_people=request.user).first()
                audit_record_obj.state = state
                audit_record_obj.audit_note = audit_note
                audit_record_obj.update_time = datetime.datetime.now()
                conference_memo_obj.current_audit_users.clear()
                audit_record_obj.save()
                if state == 'audit':
                    t_state = 'one'
                    audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit').first()
                    conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                    try:
                        RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                else:
                    t_state = 'six'
                    conference_memo_obj.current_audit_users.clear()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                conference_memo_obj.state = t_state
                conference_memo_obj.save()
                conference_memo_obj.conferencememoauditrecord_set.filter(node='PRG', state='unaudit').delete()
                returnData = {'code': 200, 'message': '操作成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'one':
                if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit', audit_people=request.user):
                    returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                conference_memo_obj.current_audit_users.clear()
                audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit').first()
                audit_record_obj.state = state
                audit_record_obj.audit_note = audit_note
                audit_record_obj.update_time = datetime.datetime.now()
                audit_record_obj.save()
                if state == 'audit':
                    if conference_memo_obj.type in ('b', 'd'):
                        if conference_memo_obj.conferencememoauditrecord_set.filter(node='YBL/DBL', state='unaudit'):
                            t_state = 'two'
                            audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='YBL/DBL', state='unaudit').first()
                            conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                            try:
                                RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                        else:
                            t_state = 'three'
                            conference_memo_obj.current_audit_users.add(User.objects.get(job_number=conference_memo_obj.apply_user.job_number))
                            try:
                                RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                    else:
                        if conference_memo_obj.conferencememoauditrecord_set.filter(node='YBL/DBL', state='unaudit'):
                            t_state = 'two'
                            audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='YBL/DBL', state='unaudit').first()
                        else:
                            t_state = 'five'
                            audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()

                        conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                        try:
                            RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type, applicant,  ApplicationTime, SubjectMatter)
                        except:
                            pass
                else:
                    t_state = 'six'
                    conference_memo_obj.current_audit_users.clear()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                conference_memo_obj.state = t_state
                conference_memo_obj.save()
                returnData = {'code': 200, 'message': '操作成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'two':
                if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YBL/DBL', state='unaudit', audit_people=request.user):
                    returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                conference_memo_obj.current_audit_users.clear()
                audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YBL/DBL', state='unaudit').first()
                audit_record_obj.state = state
                audit_record_obj.audit_note = audit_note
                audit_record_obj.update_time = datetime.datetime.now()
                audit_record_obj.save()
                if state == 'audit':
                    if conference_memo_obj.type in ('a', 'c'):
                        t_state = 'three'
                        conference_memo_obj.current_audit_users.add(User.objects.get(job_number=conference_memo_obj.apply_user.job_number))
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    elif conference_memo_obj.type in ('b', 'd'):
                        t_state = 'three'
                        conference_memo_obj.current_audit_users.add(User.objects.get(job_number=conference_memo_obj.apply_user.job_number))
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'five'
                        audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                        try:
                            RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                else:
                    t_state = 'six'
                    conference_memo_obj.current_audit_users.clear()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                conference_memo_obj.state = t_state
                conference_memo_obj.save()
                returnData = {'code': 200, 'message': '操作成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'three':
                if conference_memo_obj.type in ('a', 'b', 'c', 'd') and not hq_people:
                    returnData = {'code': 500, 'message': '需要指定会签人员！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                conference_memo_obj.current_audit_users.clear()
                if hq_people:
                    hq_people = re.findall('\((.*?)\)', hq_people)
                    hq_people_objs = User.objects.filter(job_number__in=hq_people)

                    for hq_people_obj in hq_people_objs:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj, audit_people=hq_people_obj, audit_note='', node='B')
                        conference_memo_obj.current_audit_users.add(hq_people_obj)
                        try:
                            RecordAndPush().MessagePush(hq_people_obj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass

                    conference_memo_obj.state = 'four'
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '指定会签人员成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                else:
                    if state == 'audit':
                        t_state = 'five'
                        if conference_memo_obj.type == 'e':
                            conference_memo_obj.current_audit_users.add(User.objects.get(job_number=9770))
                            try:
                                RecordAndPush().MessagePush(User.objects.get(job_number=9770).openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                        if conference_memo_obj.type in ('f', 'h'):
                            conference_memo_obj.current_audit_users.add(User.objects.get(job_number=9770))
                            try:
                                RecordAndPush().MessagePush(User.objects.get(job_number=9770).openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                        if conference_memo_obj.type == 'g':
                            conference_memo_obj.current_audit_users.add(User.objects.get(job_number=9084))
                            try:
                                RecordAndPush().MessagePush(User.objects.get(job_number=9084).openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'four':
                if conference_memo_obj.type not in ["a", "c"]:
                    if state in ['audit', 'abstention']:
                        t_state = 'five'
                        if conference_memo_obj.current_audit_users.count() == 1:
                            conference_memo_obj.current_audit_users.clear()
                            audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B', state='unaudit').first()
                            audit_record_obj.state = state
                            audit_record_obj.audit_note = audit_note
                            audit_record_obj.update_time = datetime.datetime.now()
                            audit_record_obj.save()
                            conference_memo_obj.state = t_state
                            conference_memo_obj.save()
                            next_qf_people_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                            conference_memo_obj.current_audit_users.add(next_qf_people_obj.audit_people)
                            try:
                                RecordAndPush().MessagePush(next_qf_people_obj.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                        else:
                            audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B', state='unaudit', audit_people=request.user).first()
                            audit_record_obj.state = state
                            audit_record_obj.audit_note = audit_note
                            audit_record_obj.update_time = datetime.datetime.now()
                            audit_record_obj.save()
                            conference_memo_obj.current_audit_users.remove(request.user)
                            try:
                                RecordAndPush().MessagePush(request.user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.current_audit_users.openid, topic_type, applicant,  ApplicationTime, SubjectMatter)
                        except:
                            pass
                        returnData = {'code': 200, 'message': '操作成功！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    else:
                        audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B', state='unaudit', audit_people=request.user).first()
                        audit_record_obj.state = state
                        audit_record_obj.audit_note = audit_note
                        audit_record_obj.update_time = datetime.datetime.now()
                        audit_record_obj.save()

                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        conference_memo_obj.state = t_state
                        conference_memo_obj.save()
                        if conference_memo_obj.public_search:
                            public_search_obj = conference_memo_obj.public_search
                            public_search_obj.audit_users_already.add(request.user)
                            public_search_obj.current_audit_users.clear()
                            for audit_user in conference_memo_obj.current_audit_users.all():
                                public_search_obj.current_audit_users.add(audit_user)
                                try:
                                    RecordAndPush().MessagePush(audit_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                                except:
                                    pass
                            public_search_obj.state = conference_memo_obj.state
                            public_search_obj.save()
                        returnData = {'code': 200, 'message': '操作成功！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")

                else:
                    if conference_memo_obj.current_audit_users.count() == 1:
                        conference_memo_obj.current_audit_users.clear()
                        audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B',
                                                                                                    state='unaudit').first()
                        audit_record_obj.state = state
                        audit_record_obj.audit_note = audit_note
                        audit_record_obj.update_time = datetime.datetime.now()
                        audit_record_obj.save()
                        conference_memo_obj.state = "five"
                        conference_memo_obj.save()
                        next_qf_people_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ',
                                                                                                      state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(next_qf_people_obj.audit_people)

                    else:
                        audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B',
                                                                                                    state='unaudit',
                                                                                                    audit_people=request.user).first()
                        audit_record_obj.state = state
                        audit_record_obj.audit_note = audit_note
                        audit_record_obj.update_time = datetime.datetime.now()
                        audit_record_obj.save()
                        conference_memo_obj.current_audit_users.remove(request.user)

                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'five':
                if state == 'audit':
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                    if conference_memo_obj.type in ['f', 'h', 'g']:
                        t_state = 'ten'
                        next_qf_people_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(next_qf_people_obj.audit_people)
                        try:
                            RecordAndPush().MessagePush(next_qf_people_obj.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'eight'
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                else:
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit', audit_people=request.user).first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()

                    t_state = 'six'
                    conference_memo_obj.current_audit_users.clear()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'ten':
                if state == 'audit':
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()
                    t_state = 'eight'
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                else:
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit', audit_people=request.user).first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()

                    t_state = 'six'
                    conference_memo_obj.current_audit_users.clear()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

        else:
            if conference_memo_obj.type in ['b', 'd']:
                if conference_memo_obj.state == 'one':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit', audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        t_state = 'four'
                        countersignature_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B', state='unaudit')
                        for aaa in countersignature_obj:
                            conference_memo_obj.current_audit_users.add(aaa.audit_people)
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                elif conference_memo_obj.state == 'four':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='B', state='unaudit', audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.remove(request.user)
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B', state='unaudit', audit_people=request.user).first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        print("======================", conference_memo_obj.current_audit_users.all().count())
                        if not conference_memo_obj.current_audit_users.all().count():
                            t_state = 'five'
                            yuanzhang_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                            conference_memo_obj.current_audit_users.add(yuanzhang_obj.audit_people)
                        else:
                            t_state = 'four'
                    elif state == 'abstention':
                        if not conference_memo_obj.current_audit_users.all().count():
                            t_state = 'five'
                            yuanzhang_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                            conference_memo_obj.current_audit_users.add(yuanzhang_obj.audit_people)
                        else:
                            t_state = 'four'
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                elif conference_memo_obj.state == 'five':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit', audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit', audit_people=request.user).first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        if conference_memo_obj.type == 'd':
                            t_state = 'eight'
                            conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        else:
                            if conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit'):
                                t_state = 'ten'
                                BGS_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit')
                                conference_memo_obj.current_audit_users.add(BGS_obj.audit_people)
                            else:
                                t_state = 'seven'
                                items = list()
                                if conference_memo_obj.type == 'e':
                                    for user in User.objects.all():
                                        obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=user, real_name=user.real_name, signature_picture=str(user.signature_picture), state='accept')
                                        items.append(obj)
                                    ConferenceMemoPeople.objects.bulk_create(items)
                                    returnData = {'code': 200, 'message': '操作成功！'}
                                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                                else:
                                    years = re.findall("〔(.*?)〕(.*?)号", conference_memo_obj.document_number)[0][0]
                                    topic_number = re.findall("〔(.*?)〕(.*?)号", conference_memo_obj.document_number)[0][1]
                                    print("years: ", years)
                                    print("topic_number: ", topic_number)
                                    meet_objs = topic_meeting.objects.filter(topic_type='yb', topic_year=years, meet_number=topic_number)
                                    mobiles = []
                                    has_been_sent = []
                                    for receive_people_obj in meet_objs:
                                        if receive_people_obj.topic.employee not in has_been_sent:
                                            has_been_sent.append(receive_people_obj.topic.employee)
                                            obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=receive_people_obj.topic.employee, real_name=receive_people_obj.topic.employee.real_name,
                                                                   signature_picture=str(receive_people_obj.topic.employee.signature_picture), state='accept')
                                            items.append(obj)
                                            mobiles.append(receive_people_obj.topic.employee.mobile)

                                    leaders_obj = User.objects.filter(group_id__in=[1, 2])
                                    for bbb in leaders_obj:
                                        obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=bbb, real_name=bbb.real_name, signature_picture=str(bbb.signature_picture), state='accept')
                                        items.append(obj)
                                        mobiles.append(bbb.mobile)

                                    company_obj = Company.objects.filter(id__in=[18, 22, 23])
                                    for ccc in company_obj:
                                        obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=ccc.head_people, real_name=ccc.head_people.real_name, signature_picture=str(ccc.head_people.signature_picture), state='accept')
                                        items.append(obj)
                                        mobiles.append(ccc.head_people.mobile)
                                    ConferenceMemoPeople.objects.bulk_create(items)
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass

                else:
                    if state == 'audit':
                        conference_memo_obj.current_audit_users.clear()
                        audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit').first()
                        audit_record_obj.state = state
                        audit_record_obj.audit_note = audit_note
                        audit_record_obj.update_time = datetime.datetime.now()
                        audit_record_obj.save()
                        t_state = 'seven'
                        conference_memo_obj.state = t_state
                        conference_memo_obj.save()

                        items = list()
                        if conference_memo_obj.type == 'e':
                            for user in User.objects.filter(~Q(id__in=[2, 3]), is_delete=0):
                                obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=user, real_name=user.real_name, signature_picture=str(user.signature_picture), state='accept')
                                items.append(obj)
                            ConferenceMemoPeople.objects.bulk_create(items)
                            returnData = {'code': 200, 'message': '操作成功！'}
                            return HttpResponse(json.dumps(returnData), content_type="application/json")
                        else:
                            years = re.findall("〔(.*?)〕(.*?)号", conference_memo_obj.document_number)[0][0]
                            topic_number = re.findall("〔(.*?)〕(.*?)号", conference_memo_obj.document_number)[0][1]
                            meet_objs = topic_meeting.objects.filter(topic_type='yb', topic_year=years, meet_number=topic_number)
                            mobiles = []
                            for receive_people_obj in meet_objs:
                                obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=receive_people_obj.employee,
                                                           real_name=receive_people_obj.employee.real_name, signature_picture=str(receive_people_obj.employee.signature_picture), state='accept')
                                items.append(obj)
                                mobiles.append(receive_people_obj.mobile)

                            leaders_obj = User.objects.filter(group_id__in=[1, 2])
                            for bbb in leaders_obj:
                                obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=bbb,  real_name=bbb.real_name, signature_picture=str(bbb.signature_picture), state='accept')
                                items.append(obj)
                                mobiles.append(bbb.mobile)

                            company_obj = Company.objects.filter(id__in=[18, 22, 23])
                            for ccc in company_obj:
                                obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=ccc, real_name=ccc.real_name, signature_picture=str(ccc.signature_picture), state='accept')
                                items.append(obj)
                                mobiles.append(ccc.mobile)
                            ConferenceMemoPeople.objects.bulk_create(items)

                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                        returnData = {'code': 200, 'message': '操作成功！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    else:
                        audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit', audit_people=request.user).first()
                        audit_record_obj.state = state
                        audit_record_obj.audit_note = audit_note
                        audit_record_obj.update_time = datetime.datetime.now()
                        audit_record_obj.save()

                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                        conference_memo_obj.state = t_state
                        conference_memo_obj.save()
                        returnData = {'code': 200, 'message': '操作成功！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")

                conference_memo_obj.state = t_state
                conference_memo_obj.save()
                returnData = {'code': 200, 'message': '操作成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif conference_memo_obj.type == 'e':
                if conference_memo_obj.state == 'nine':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit', audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit', audit_people=request.user).first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj.save()
                    conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit').delete()
                    if state == 'audit':
                        t_state = 'one'
                        audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                        try:
                            RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

                if conference_memo_obj.state == 'one':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit', audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        t_state = "five"
                        next_qf_people_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(next_qf_people_obj.audit_people)
                        try:
                            RecordAndPush().MessagePush(next_qf_people_obj.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

                if conference_memo_obj.state == 'five':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit', audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        t_state = "eight"
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                if conference_memo_obj.state == 'nine':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit', audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit', audit_people=request.user).first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj.save()
                    conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit').delete()
                    if state == 'audit':
                        t_state = 'one'
                        audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                        try:
                            RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

                if conference_memo_obj.state == 'one':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit', audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        t_state = "five"
                        next_qf_people_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(next_qf_people_obj.audit_people)
                        try:
                            RecordAndPush().MessagePush(next_qf_people_obj.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

                if conference_memo_obj.state == 'five':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit', audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        t_state = "ten"
                        next_qf_people_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(next_qf_people_obj.audit_people)
                        try:
                            RecordAndPush().MessagePush(next_qf_people_obj.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

                if conference_memo_obj.state == 'ten':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit', audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        t_state = "eight"
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")


class ConferenceMemoReceive(View):
    def post(self, request):
        id = request.POST.get('id', None)
        receive_people = request.POST.get('receive_people', None)
        conference_memo_obj = ConferenceMemo.objects.get(id=id)
        conference_memo_obj.state = 'seven'
        conference_memo_obj.save()
        conference_memo_obj.current_audit_users.clear()
        items = list()
        if not receive_people:
            returnData = {'code': 200, 'message': '需收阅指定人员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        receive_people = re.findall('\((.*?)\)', receive_people)
        receive_people_objs = User.objects.filter(job_number__in=receive_people)
        mobiles = []
        for receive_people_obj in receive_people_objs:
            obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=receive_people_obj,
                                       real_name=receive_people_obj.real_name,
                                       signature_picture=str(receive_people_obj.signature_picture),
                                       state='accept')
            items.append(obj)
            mobiles.append(receive_people_obj.mobile)
        ConferenceMemoPeople.objects.bulk_create(items)
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ConferenceMemoWriteView(View):
    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        document_number = request.POST.get('document_number', None)
        number = request.POST.get('number', None)
        type = request.POST.get('type', None)  # 类型
        main_company = request.POST.get('main_company', '')
        vice_company = request.POST.get('vice_company', '')
        servings = request.POST.get('servings', None)  # 分数
        conference_memo_text = request.POST.get('conference_memo_text', None)  # 事由
        gist = request.POST.get('gist')
        # drafter = request.POST.get('drafter', None)  # 拟稿人

        obj = ConferenceMemo.objects.get(id=int(id))
        if obj.state != 'six' and obj.conferencememoauditrecord_set.filter(
                Q(state='draft') | Q(state='audit')).count() != 0:
            returnData = {'code': 500, 'message': '修改错误，只有为拒绝和新建的状态公文才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        try:
            if document_number:
                obj.document_number = document_number
            if number:
                obj.topics_name = number
            if type:
                obj.type = type
            if main_company:
                obj.main_company = main_company
            if vice_company:
                obj.vice_company = vice_company
            if servings:
                obj.servings = int(servings)
            if gist:
                obj.gist = gist
            if conference_memo_text:
                obj.conference_memo_text = conference_memo_text
            obj.state = 'one'
            obj.current_audit_users.clear()
            obj.conferencememoauditrecord_set.filter(state="unaudit").delete()
            dbzr = Company.objects.get(id=3).head_people
            obj.current_audit_users.add(dbzr)
            if obj.type in ('f', 'g', 'h'):
                obj.state = 'nine'
                obj.save()
                obj.current_audit_users.remove(dbzr)
                com_obj = Company.objects.filter(name=obj.drafter_company).first()

                if com_obj.id in [3, 80]:
                    nine_people = Staffing.objects.get(station="党政办工作人员").post_personnel.all()
                    for ni_pe in nine_people:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=ni_pe, audit_note='', node='C/D')
                        obj.current_audit_users.add(ni_pe)
                else:
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=com_obj.head_people, audit_note='', node='C/D')
                    obj.current_audit_users.add(com_obj.head_people)
                if obj.type == "g":
                    prg_people = Staffing.objects.get(station="党委办公室").post_personnel.all()
                    for Prg in prg_people:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=Prg, audit_note='', node='PRG')
                else:
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=request.user, audit_note='', node='PRG')
            ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=dbzr, audit_note='', node='YB/DB')
            if obj.type in ('a', 'c'):
                dzb_leader = Company.objects.get(id=3).leaders_id
                ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=dzb_leader, audit_note='', node='YBL/DBL')
                ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=Staffing.objects.get(station="书记").post_personnel.all().first(), audit_note='', node='YZ/SJ')
            elif obj.type in ('b', 'd', 'e'):
                if obj.type not in ['b', 'd']:
                    yzb_leader = Company.objects.get(id=80).leaders_id
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=yzb_leader, audit_note='', node='YBL/DBL')
                ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), audit_note='', node='YZ/SJ')
            else:
                if obj.fg_people:
                    if request.user.company.id != 80:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=obj.fg_people, audit_note='', node='YBL/DBL')
                    else:
                        com_obj = Company.objects.filter(name=obj.drafter_company).first()
                        if com_obj.id not in [3, 80]:
                            ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=obj.fg_people, audit_note='', node='YBL/DBL')
                else:
                    returnDict = {'code': 500, 'message': '请传分管领导！'}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
                if obj.type in ['g', 'i']:
                    if obj.type == 'g':
                        BGS_appave = Staffing.objects.get(station='党委印章管理员').post_personnel.all().first()
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=BGS_appave, audit_note='', node='BGS')
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=Staffing.objects.get(station="书记").post_personnel.all().first(), audit_note='', node='YZ/SJ')
                else:
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=obj.qf_people, audit_note='', node='YZ/SJ')
                    BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                    ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj, audit_people=BGS_appave, audit_note='', node='BGS')

            obj.save()
            topic_type = "公文审批"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.conference_memo_text[:15] + "……" if len(obj.conference_memo_text) > 15 else obj.conference_memo_text
            try:
                RecordAndPush().MessagePush(obj.current_audit_users.all().first().openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass

            returnDict = {'code': 200, 'message': '修改成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        except Exception as e:
            obj.state = 'six'
            obj.save()
            returnData = {'code': 500, 'message': '修改错误'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class ConferenceMemoCancelView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = ConferenceMemo.objects.get(id=int(id))
        if state == 'recall':
            if obj.conferencememoauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的公文才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            obj.current_audit_users.clear()
            obj.state = 'recall'
            obj.save()
            sequence_obj = Sequence.objects.filter(type=obj.type).first()
            conferencememo_objs = ConferenceMemo.objects.filter(create_time__gt=obj.create_time, type=obj.type)
            for conferencememo_obj in conferencememo_objs:
                num = re.findall("〕(.*?)号", conferencememo_obj.document_number)[0]
                if conferencememo_obj.type == 'h':
                    conferencememo_number = '京医文〔' + str(datetime.datetime.now().year) + '〕' + str(int(num) - 1) + '号'
                elif conferencememo_obj.type == 'f':
                    conferencememo_number = '京医发〔' + str(datetime.datetime.now().year) + '〕' + str(int(num) - 1) + '号'
                elif conferencememo_obj.type == 'f':
                    conferencememo_number = '京医党发〔' + str(datetime.datetime.now().year) + '〕' + str(int(num) - 1) + '号'
                else:
                    conferencememo_number = '会议纪要〔' + str(datetime.datetime.now().year) + '〕' + str(int(num) - 1) + '号'
                conferencememo_obj.document_number = conferencememo_number
                conferencememo_obj.save()
            if sequence_obj:
                sequence_obj.sequence -= 1
                sequence_obj.next_sequence -= 1
                sequence_obj.save()
        elif state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的公文才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'cancel'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的公文不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '状态不正确！操作失败'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ConferenceMemoBackView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)
        audit_people = request.POST.get('audit_people', None)
        audit_people = re.findall('\((.*?)\)', audit_people)
        audit_people_objs = User.objects.filter(job_number__in=audit_people)
        obj = ConferenceMemo.objects.get(id=int(id))
        if state != 'four' and audit_people_objs.count() > 1:
            returnData = {'code': 500, 'message': '只有会签状态才能选择多个审批人！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        # if state == obj.state:
            # returnData = {'code': 200, 'message': 'ok！'}
            # return HttpResponse(json.dumps(returnData), content_type="application/json")
        if obj.state in ('cancel', 'six'):
            returnData = {'code': 500, 'message': '已经作废或拒绝的单据，不能退回！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            if state == 'nine':
                if obj.type not in ('f', 'g', 'h'):
                    returnData = {'code': 500, 'message': '该公文类型不需要科室初审！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                obj.conferencememopeople_set.all().delete()
                obj.current_audit_users.clear()
                if audit_people_objs.count() > 0:
                    obj.conferencememoauditrecord_set.filter(node='C/D').delete()
                    for audit_people_obj in audit_people_objs:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj,
                                                                 audit_people=audit_people_obj,
                                                                 audit_note='', node='C/D')
                audit_user = obj.conferencememoauditrecord_set.filter(node='C/D').first().audit_people
                obj.current_audit_users.add(audit_user)
                b_audit_objs = obj.conferencememoauditrecord_set.filter(node='B')
                for audit_obj in b_audit_objs:
                    audit_obj.delete()
                audit_objs = obj.conferencememoauditrecord_set.all()
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'one':
                if obj.state == 'nine':
                    returnData = {'code': 500, 'message': '只能退回！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                obj.conferencememopeople_set.all().delete()
                obj.current_audit_users.clear()
                if audit_people_objs.count() > 0:
                    obj.conferencememoauditrecord_set.filter(node='YB/DB').delete()
                    for audit_people_obj in audit_people_objs:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj,
                                                                 audit_people=audit_people_obj,
                                                                 audit_note='', node='YB/DB')
                audit_user = obj.conferencememoauditrecord_set.filter(node='YB/DB').first().audit_people
                obj.current_audit_users.add(audit_user)
                b_audit_objs = obj.conferencememoauditrecord_set.filter(node='B')
                for audit_obj in b_audit_objs:
                    audit_obj.delete()
                audit_objs = obj.conferencememoauditrecord_set.filter(node__in=['YB/DB', 'YZ/SJ', 'YBL/DBL'])
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'two':
                if obj.state in ('nine', 'one'):
                    returnData = {'code': 500, 'message': '只能退回！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                obj.conferencememopeople_set.all().delete()
                obj.current_audit_users.clear()
                if audit_people_objs.count() > 0:
                    obj.conferencememoauditrecord_set.filter(node='YBL/DBL').delete()
                    for audit_people_obj in audit_people_objs:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj,
                                                                 audit_people=audit_people_obj,
                                                                 audit_note='', node='YBL/DBL')
                audit_user = obj.conferencememoauditrecord_set.filter(node='YBL/DBL').first().audit_people
                obj.current_audit_users.add(audit_user)
                b_audit_objs = obj.conferencememoauditrecord_set.filter(node='B')
                for audit_obj in b_audit_objs:
                    audit_obj.delete()
                audit_objs = obj.conferencememoauditrecord_set.filter(node__in=['YBL/DBL', 'YZ/SJ'])
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'three':
                if obj.state in ('nine', 'one', 'two'):
                    returnData = {'code': 500, 'message': '只能退回！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                obj.conferencememopeople_set.all().delete()
                obj.current_audit_users.clear()
                if audit_people_objs.count() > 0:
                    returnData = {'code': 500, 'message': '只能由申请人指定会签人员,无需修改审批人！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                # audit_user = obj.conferencememoauditrecord_set.filter(node='YBL/DBL').first().audit_people
                obj.current_audit_users.add(obj.apply_user)
                b_audit_objs = obj.conferencememoauditrecord_set.filter(node='B')
                for audit_obj in b_audit_objs:
                    audit_obj.delete()
                audit_objs = obj.conferencememoauditrecord_set.filter(node__in=['YZ/SJ'])
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'four':
                if obj.state in ('nine', 'one', 'two', 'three'):
                    returnData = {'code': 500, 'message': '只能退回！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                obj.conferencememopeople_set.all().delete()
                obj.current_audit_users.clear()
                if audit_people_objs.count() > 0:
                    obj.conferencememoauditrecord_set.filter(node='B').delete()
                    for audit_people_obj in audit_people_objs:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj,
                                                                 audit_people=audit_people_obj,
                                                                 audit_note='', node='B')
                audit_users = obj.conferencememoauditrecord_set.filter(node='B')
                for audit_user in audit_users:
                    obj.current_audit_users.add(audit_user.audit_people)
                audit_objs = obj.conferencememoauditrecord_set.filter(node__in=['YZ/SJ', 'B'])
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'five':
                if obj.state in ('nine', 'one', 'two', 'three', 'four'):
                    returnData = {'code': 500, 'message': '只能退回！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                obj.conferencememopeople_set.all().delete()
                obj.current_audit_users.clear()
                if audit_people_objs.count() > 0:
                    obj.conferencememoauditrecord_set.filter(node='YZ/SJ').delete()
                    for audit_people_obj in audit_people_objs:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=obj,
                                                                 audit_people=audit_people_obj,
                                                                 audit_note='', node='YZ/SJ')
                audit_user = obj.conferencememoauditrecord_set.filter(node='YZ/SJ').first().audit_people
                obj.current_audit_users.add(audit_user)
                audit_objs = obj.conferencememoauditrecord_set.filter(node__in=['YZ/SJ'])
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'six':
                b_audit_objs = obj.conferencememoauditrecord_set.filter(node='B')
                for audit_obj in b_audit_objs:
                    audit_obj.delete()
                audit_objs = obj.conferencememoauditrecord_set.all()
                for audit_obj in audit_objs:
                    audit_obj.audit_note = ''
                    audit_obj.state = 'unaudit'
                    audit_obj.save()
                if audit_people_objs.count() > 0:
                    returnData = {'code': 500, 'message': '无需修改审批人！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)
                obj.state = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                returnData = {'code': 500, 'message': '请选择正确的状态！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")


class ConferenceMemoStopView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = ConferenceMemo.objects.get(id=int(id))
        if obj.apply_user != request.user:
            returnData = {'code': 500, 'message': '终止失败！只有申请人才能终止流程'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_users.clear()
        obj.state = 'stop'
        obj.save()
        returnData = {'code': 200, 'message': '成功终止！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class OfficialDocumentsListView(View):
    def get(self, request):
        user = request.user
        page = request.GET.get('page', 1)
        cuent_type = request.GET.get('cuent_type', '0')
        my_apply_objs = user.officialdocuments_set.all().order_by('-create_time')
        audit_objs = user.official_documents_users.all().order_by('-create_time')
        already_audit_objs = user.official_documents_already_audit_users.all().order_by('-create_time')

        my_apply_list = [{'id': record.id, 'send_company': record.send_company, 'send_number': record.send_number, 'recive_number': record.recive_number,
                          'recive_time': record.recive_time.strftime("%Y-%m-%d"), 'title': record.title,
                          'state': record.get_type_display(), "type": record.state, "is_stop": True if user in record.current_audit_users.all() or record.officialdocumentsauditrecord_set.filter(state__in=['draft', 'audit']).count() == 0 else False,
                          'audit_user': ' ,'.join([i.real_name for i in record.current_audit_users.all()])} for record
                         in my_apply_objs]
        audit_list = [{'id': record.id, 'send_company': record.send_company, 'send_number': record.send_number,
                       'recive_time': record.recive_time.strftime("%Y-%m-%d"), 'title': record.title,
                       'state': record.get_type_display(), "type": record.state,
                       'audit_user': ' ,'.join([i.real_name for i in record.current_audit_users.all()])} for record
                      in audit_objs[(int(page) - 1) * 20:int(page) * 20]]
        already_audit_list = [{'id': record.id, 'send_company': record.send_company, 'send_number': record.send_number,
                               'recive_time': record.recive_time.strftime("%Y-%m-%d"), 'title': record.title,
                               'state': record.get_type_display(), "type": record.state,
                               'audit_user': ' ,'.join([i.real_name for i in record.current_audit_users.all()])} for
                              record
                              in already_audit_objs[(int(page) - 1) * 20:int(page) * 20]]

        shenpizhong, chuanyuezhong, yiwanjie, daifenfa = [], [], [], []
        for i in my_apply_list:
            if i['state'] in ['分管领导签批', '院长/书记审核', '办公室主任审核', '终止']:
                shenpizhong.append(i)
            elif i['state'] in ['科主任传阅']:
                chuanyuezhong.append(i)
            elif i["state"] in ["待分发"]:
                daifenfa.append(i)
            else:
                yiwanjie.append(i)
        my_apply_list = shenpizhong + daifenfa + chuanyuezhong + yiwanjie

        if cuent_type == '0':
            returnData = {'code': 200, 'message': '获取成功！', 'my_apply_list': my_apply_list[(int(page) - 1) * 20:int(page) * 20], 'audit_list': audit_list,
                          'already_audit_list': already_audit_list, 'my_apply_list_len': my_apply_objs.count(),
                          'already_audit_list_len': already_audit_objs.count(), 'audit_len': audit_objs.count()}
        elif cuent_type == '1':
            returnData = {'code': 200, 'message': '获取成功！', 'my_apply_list': my_apply_list, 'my_apply_list_len': my_apply_objs.count()}
        elif cuent_type == '2':
            returnData = {'code': 200, 'message': '获取成功！', 'audit_list': audit_list, 'audit_len': audit_objs.count()}
        else:
            returnData = {'code': 200, 'message': '获取成功！', 'already_audit_list': already_audit_list, 'already_audit_list_len': already_audit_objs.count()}

        return HttpResponse(json.dumps(returnData), content_type="application/json")


class OfficialDocumentsView(View):
    def get(self, request):
        user = request.user
        page = request.GET.get("page", 1)
        cuent_type = request.GET.get('cuent_type', '0')
        accept_objs = user.officialdocumentspeople_set.filter(state='accept').order_by("-create_time")
        accepted_objs = user.officialdocumentspeople_set.filter(state='accepted').order_by("-create_time")
        end_objs = OfficialDocuments.objects.filter(type='e').order_by("-create_time")
        accept_objs = [record.notice_id for record in accept_objs]
        accept_list = [{'id': record.id, 'send_company': record.send_company, 'send_number': record.send_number,
                        'recive_time': record.recive_time.strftime("%Y-%m-%d"), 'title': record.title,
                        'state': record.get_type_display(), 'recive_number': record.recive_number,
                        'user': record.apply_user.real_name, 'department': record.apply_user.company.name,
                        'create_time': record.create_time.strftime("%Y-%m-%d %H:%M"),
                        } for record
                       in accept_objs[(int(page) - 1) * 20:int(page) * 20]]
        accepted_objs = [record.notice_id for record in accepted_objs]
        accepted_list = [{'id': record.id, 'send_company': record.send_company, 'send_number': record.send_number,
                          'recive_time': record.recive_time.strftime("%Y-%m-%d"), 'title': record.title,
                          'state': record.get_type_display(), 'recive_number': record.recive_number,
                          'user': record.apply_user.real_name, 'department': record.apply_user.company.name,
                          'create_time': record.create_time.strftime("%Y-%m-%d %H:%M"),
                          } for record
                         in accepted_objs[(int(page) - 1) * 20:int(page) * 20]]

        end_list = [{'id': record.id, 'send_company': record.send_company, 'send_number': record.send_number,
                     'recive_time': record.recive_time.strftime("%Y-%m-%d"), 'title': record.title,
                     'state': record.get_type_display(), 'recive_number': record.recive_number,
                     'user': record.apply_user.real_name, 'department': record.apply_user.company.name,
                     'create_time': record.create_time.strftime("%Y-%m-%d %H:%M"),
                     } for record
                    in end_objs[(int(page) - 1) * 20:int(page) * 20]]

        if cuent_type == '0':
            returnData = {'code': 200, 'message': '获取成功！', 'accept_list': accept_list, 'len_accept': len(accept_objs), 'accepted_list': accepted_list, 'len_accepted_list': len(accepted_objs), 'end_list': end_list, 'end_list_len': end_objs.count()}
        elif cuent_type == '1':
            returnData = {'code': 200, 'message': '获取成功！', 'accept_list': accept_list, 'len_accept': len(accept_objs)}
        elif cuent_type == '2':
            returnData = {'code': 200, 'message': '获取成功！', 'accepted_list': accepted_list, 'len_accepted_list': len(accepted_objs)}
        else:
            returnData = {'code': 200, 'message': '获取成功！', 'end_list': end_list, 'end_list_len': end_objs.count()}

        return HttpResponse(json.dumps(returnData), content_type="application/json")

    def post(self, request):
        send_number = request.POST.get('send_number', None)
        recive_number = request.POST.get('recive_number', None)
        send_company = request.POST.get('send_company', None)
        recive_time = request.POST.get('recive_time', None)
        title = request.POST.get('title', None)
        content = request.POST.get('content', None)
        annotated_text = request.POST.get('annotated_text', '')
        time_limit = request.POST.get('time_limit', '')
        uuid = request.POST.get('uuid', '')
        rake_up = request.POST.get("rake_up", None)
        beizhu = request.POST.get("beizhu", None)
        leaders_people = request.POST.get("leaders_people", None)
        charge_flag = request.POST.get("charge_flag", None)
        notification = request.POST.get("notification", '')
        ReadLeadershipList = request.POST.get("read_leadership_list", None)
        today_data = time.strftime("%Y-%m-%d", time.localtime())
        today = datetime.datetime.now().date()
        lw_count = today_data + "-" + str(OfficialDocuments.objects.filter(~Q(state='recall'), create_time__gt=today).count() + 1)

        recive_time = datetime.datetime.now().strptime(recive_time, '%Y-%m-%d %H:%M:%S')
        if rake_up:
            official_documents_obj = OfficialDocuments.objects.get(uuid=uuid)
            official_documents_obj.current_audit_users.clear()
            official_documents_obj.officialdocumentsauditrecord_set.filter(state='unaudit').delete()
            official_documents_obj.notification_class = notification
            official_documents_obj.recive_time = recive_time
            official_documents_obj.send_company = send_company
            official_documents_obj.title = title
            official_documents_obj.content = content
            official_documents_obj.annotated_text = annotated_text
            official_documents_obj.time_limit = time_limit
            official_documents_obj.remarks = beizhu
            official_documents_obj.type='a'
            official_documents_obj.state = 'a'
            official_documents_obj.save()

        else:
            official_documents_obj = OfficialDocuments.objects.create(apply_user=request.user, send_number=send_number, recive_number=lw_count,
                                                                  send_company=send_company, recive_time=recive_time, title=title, notification_class=notification,
                                                                  content=content, annotated_text=annotated_text, time_limit=time_limit, uuid=uuid, remarks=beizhu)

        read_leader_ship_list = ReadLeadershipList.split(",")
        for read_leader in read_leader_ship_list:
            if read_leader.strip():
                receive_people_objs = User.objects.get(id=int(read_leader.strip()))
                OfficialDocumentsPeople.objects.create(notice_id=official_documents_obj, state='accept', audit_people=receive_people_objs)

        if notification == '1':
            official_documents_obj.type = 'e'
            official_documents_obj.state = 'six'
            official_documents_obj.save()
            returnData = {'code': 200, 'message': '创建成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        if charge_flag == "True" or request.user == request.user.company.head_people:
            official_documents_obj.state = "two"
            openid = ''
            leaders_people_list = leaders_people.split(",")
            for yy in leaders_people_list:
                if yy.strip():
                    leader_charge = User.objects.get(id=int(yy.strip()))
                    official_documents_obj.leaders = leader_charge
                    official_documents_obj.current_audit_users.add(leader_charge)
                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=official_documents_obj, state="unaudit", audit_people=leader_charge, node="two")
                    openid = leader_charge.openid
        else:
            official_documents_obj.state = "one"
            official_documents_obj.current_audit_users.add(request.user.company.head_people)
            OfficialDocumentsAuditRecord.objects.create(official_documents_id=official_documents_obj, state="unaudit", audit_people=request.user.company.head_people, node="one")
            openid = request.user.company.head_people.openid

        topic_type = "上级来文"
        applicant = official_documents_obj.apply_user.real_name
        ApplicationTime = official_documents_obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = official_documents_obj.title[:15] + "……" if len(official_documents_obj.title) > 15 else official_documents_obj.title
        try:
            RecordAndPush().MessagePush(openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        except:
            pass
        official_documents_obj.save()
        returnData = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class OfficialDocumentsDetailView(View):
    def get(self, request):
        id = request.GET.get('id', None)
        obj = OfficialDocuments.objects.get(id=int(id))
        audit_dic = {}
        p_obj = obj.officialdocumentspeople_set.filter(audit_people=request.user,
                                                       state='accept').first()
        if p_obj:
            p_obj.state = 'accepted'
            p_obj.update_time = datetime.datetime.now()
            p_obj.save()

        if obj.officialdocumentspeople_set.filter(state='accept').count() == 0 and obj.type == 'd':
            obj.type = 'e'
            obj.save()

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", '/'),
                      "pdf_path": atta_obj.pdf_path.replace("\\", '/'),
                      "file_size": atta_obj.file_size,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      'word_path': os.getcwd() + "/media/" + str(atta_obj.file_path).replace("\\", '/'),
                      "uploader": atta_obj.uploader_user.real_name, "id": atta_obj.id,
                      "topics_number": atta_obj.topics_number} for
                     atta_obj in
                     Topicsattachments.objects.filter(topics_number=obj.uuid, file_type="0")]

        file_list1 = [{"file_name": atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", '/')} for
                      atta_obj in
                      Topicsattachments.objects.filter(topics_number=obj.uuid, file_type="1")]

        for audit_obj in obj.officialdocumentsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.get_state_display(),
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state': audit_obj.get_state_display(),
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        recive_people = [{'user': record.audit_people.real_name, 'state': record.get_state_display(),
                          'signature_picture': '/media/' + str(
                              record.audit_people.signature_picture) if (
                                  record.audit_people.signature_picture and record.state == 'accepted') else '',
                          'update_time': record.update_time.strftime("%Y-%m-%d %H:%M") if record.state == 'accepted' else ''}
                         for record in obj.officialdocumentspeople_set.all()]
        staff_obj = Staffing.objects.filter(station="办公室")

        flag = 0
        if staff_obj:
            for tt in staff_obj:
                personnel = tt.post_personnel.all()
                for jj in personnel:
                    if jj == request.user:
                        flag = 1

        data_dic = {
            'id': obj.id,
            'node': obj.get_type_display(),
            'type': obj.type,
            'apply_user': obj.apply_user.real_name,
            'department': obj.apply_user.company.name,
            'send_number': obj.send_number,
            'recive_number': obj.recive_number,
            'title': obj.title,
            "uuid": obj.uuid,
            'send_company': obj.send_company,
            'content': obj.content,
            'annotated_text': obj.annotated_text,
            'time_limit': obj.time_limit,
            'remarks': obj.remarks,
            'audit_dic': audit_dic,
            'recive_people': recive_people,
            'file_list': file_list,
            'flag': flag,
            'file_list1': file_list1,
            'recive_time': obj.recive_time.strftime("%Y-%m-%d %H:%M"),
            'revocation_flag' : 'true',  # 撤回标签，’true‘ 有该权限
            'is_stop': 'true' if obj.type in ['a', 'b', 'c', 'f', 'g', 'h'] and request.user == obj.apply_user else 'false',
        }
        returnDict = {'code': 200, 'message': '获取成功', 'data_dic': data_dic}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get("state", 'audit')                                            # draft 拒绝 audit 通过
        audit_note = request.POST.get('audit_note', '同意')
        fg_people = request.POST.get('fg_people', None)                                                          # 分管人员
        type = request.POST.get('type', None)                                                # a 留文归档 b 拟办意见 c 党办 d 院办
        obj = OfficialDocuments.objects.get(id=int(id))

        topic_type = "上级来文"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        RecordAndPush().OperationRecords(request, topic_type)
        if not type and obj.type == 'a':
            returnDict = {'code': 500, 'message': '办公室主任审核需指定类型'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.audit_users_already.add(request.user)

        if type and obj.type == 'a':
            obj.current_audit_users.clear()
            audit_record_obj = obj.officialdocumentsauditrecord_set.filter(node='YB', state='unaudit').first()
            audit_record_obj.update_time = datetime.datetime.now()
            audit_record_obj.state = 'audit'
            audit_record_obj.audit_note = audit_note
            audit_record_obj.save()
            obj.state = type
            obj.officialdocumentsauditrecord_set.filter(state='unaudit').delete()
            if type == 'a':
                obj.type = 'e'
                obj.save()
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            elif type == 'b':
                obj.type = 'c'
                obj.save()

                fg_people = re.findall('\((.*?)\)', fg_people)
                fg_people_objs = User.objects.filter(job_number__in=fg_people)

                for fg_people_obj in fg_people_objs:
                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, audit_people=fg_people_obj, audit_note='', node='B')
                    obj.current_audit_users.add(fg_people_obj)
                    try:
                        RecordAndPush().MessagePush(fg_people_obj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            elif type == 'c':
                obj.type = 'b'
                obj.save()
                audit_record_obj.audit_note = audit_note
                audit_record_obj.save()
                obj.current_audit_users.add(Staffing.objects.get(station="书记").post_personnel.all().first())
                OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state='unaudit', node='YZ/SJ', audit_note='', audit_people=Staffing.objects.get(station="书记").post_personnel.all().first())
                try:
                    RecordAndPush().MessagePush(Staffing.objects.get(station="书记").post_personnel.all().first().openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            elif type == 'd':
                obj.type = 'b'
                obj.save()
                audit_record_obj.audit_note = audit_note
                audit_record_obj.save()
                obj.current_audit_users.add(Staffing.objects.get(station="院长").post_personnel.all().first())
                OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state='unaudit', node='YZ/SJ', audit_note='', audit_people=Staffing.objects.get(station="院长").post_personnel.all().first())
                try:
                    RecordAndPush().MessagePush(Staffing.objects.get(station="院长").post_personnel.all().first().openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            elif type == 'e':
                obj.type = 'b'
                obj.save()
                audit_record_obj.audit_note = audit_note
                audit_record_obj.save()
                yz_obj = Staffing.objects.get(station="院长").post_personnel.all().first()
                sj_obj = Staffing.objects.get(station="书记").post_personnel.all().first()

                OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state='unaudit', node='YZ/SJ', audit_note='', audit_people=yz_obj)
                OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state='unaudit', node='YZ/SJ', audit_note='', audit_people=sj_obj)
                obj.current_audit_users.add(yz_obj)
                try:
                    RecordAndPush().MessagePush(yz_obj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
                obj.current_audit_users.add(sj_obj)
                try:
                    RecordAndPush().MessagePush(sj_obj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            elif type == 'f':
                unagree_official(obj, audit_record_obj, audit_note, request)
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            elif type == 'g':
                items = []
                receive_people = re.findall('\((.*?)\)', fg_people)
                receive_people_objs = User.objects.filter(job_number__in=receive_people, is_delete="0")
                mobile_list = []
                for receive_people_obj in receive_people_objs:
                    mobile_list.append(receive_people_obj.mobile)
                    off_obj = OfficialDocumentsPeople(notice_id=obj, state='accept', audit_people=receive_people_obj)
                    items.append(off_obj)
                obj.current_audit_users.clear()
                OfficialDocumentsPeople.objects.bulk_create(items)
                if receive_people:
                    obj.type = 'd'
                else:
                    obj.type = 'e'
                obj.save()
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            else:
                returnDict = {'code': 500, 'message': '指定类型错误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        elif obj.type == 'b':
            audit_record_list = obj.officialdocumentsauditrecord_set.filter(node='YZ/SJ', state='unaudit')
            audit_record_obj = None
            for i in audit_record_list:
                if i.audit_people == request.user:
                    audit_record_obj = i
            if state == 'audit':
                if audit_record_list.count() == 1:
                    obj.current_audit_users.clear()
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.state = 'audit'
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.save()
                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, audit_people=obj.apply_user, audit_note='', node='SQ')
                    obj.current_audit_users.add(obj.apply_user)
                    obj.type = 'h'
                    obj.save()
                    try:
                        RecordAndPush().MessagePush(obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                else:
                    obj.current_audit_users.remove(request.user)
                    audit_record_obj.update_time = datetime.datetime.now()
                    audit_record_obj.state = 'audit'
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.save()

                returnDict = {'code': 200, 'message': '操作成功'}

                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            else:
                unagree_official(obj, audit_record_obj, audit_note, request)
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        elif obj.type == 'c':
            audit_record_obj = obj.officialdocumentsauditrecord_set.filter(node='B', audit_people=request.user, state='unaudit').first()
            if state == 'audit':
                audit_record_obj.update_time = datetime.datetime.now()
                audit_record_obj.state = 'audit'
                audit_record_obj.audit_note = audit_note
                audit_record_obj.save()
                obj.current_audit_users.remove(request.user)
                if obj.officialdocumentsauditrecord_set.filter(state='unaudit', node='B'):
                    pass
                else:
                    obj.current_audit_users.clear()
                    obj.current_audit_users.add(obj.apply_user)
                    obj.type = 'g'
                    obj.save()
                    try:
                        RecordAndPush().MessagePush(obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            else:
                unagree_official(obj, audit_record_obj, audit_note, request)
                returnDict = {'code': 200, 'message': '操作成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        elif obj.type == 'h':
            audit_record_obj = obj.officialdocumentsauditrecord_set.filter(node='SQ', state='unaudit').first()

            obj.current_audit_users.clear()
            audit_record_obj.update_time = datetime.datetime.now()
            audit_record_obj.state = 'audit'
            audit_record_obj.audit_note = audit_note
            audit_record_obj.save()
            fg_people = re.findall('\((.*?)\)', fg_people)
            fg_people_objs = User.objects.filter(job_number__in=fg_people)

            for fg_people_obj in fg_people_objs:
                OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, audit_people=fg_people_obj, audit_note='', node='B')
                obj.current_audit_users.add(fg_people_obj)
                try:
                    RecordAndPush().MessagePush(fg_people_obj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
            obj.type = 'c'
            obj.save()
            returnDict = {'code': 200, 'message': '操作成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        else:
            print("参数错误")
            returnDict = {'code': 500, 'message': '参数错误'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


def unagree_official(obj, audit_record_obj, audit_note, request):
    """上级来文退回调用函数"""
    obj.current_audit_users.clear()
    obj.current_audit_users.add(obj.apply_user)
    obj.type = 'f'
    obj.save()
    audit_record_obj.update_time = datetime.datetime.now()
    audit_record_obj.state = 'draft'
    audit_record_obj.audit_note = audit_note
    audit_record_obj.save()
    if obj.public_search:
        public_search_obj = obj.public_search
        public_search_obj.audit_users_already.add(request.user)
        public_search_obj.current_audit_users.clear()
        for audit_user in obj.current_audit_users.all():
            public_search_obj.current_audit_users.add(audit_user)
        public_search_obj.state = obj.state
        public_search_obj.save()


class OfficialDocumentsReceive(View):
    def post(self, request):
        id = request.POST.get('id', None)
        receive_people = request.POST.get('receive_people', None)
        message = request.POST.get('message', None)
        obj = OfficialDocuments.objects.get(id=int(id))
        items = []
        receive_people = re.findall('\((.*?)\)', receive_people)
        receive_people_objs = User.objects.filter(job_number__in=receive_people, is_delete="0")
        mobile_list = []
        for receive_people_obj in receive_people_objs:
            mobile_list.append(receive_people_obj.mobile)
            off_obj = OfficialDocumentsPeople(notice_id=obj, state='accept', audit_people=receive_people_obj)
            items.append(off_obj)
        obj.current_audit_users.clear()
        OfficialDocumentsPeople.objects.bulk_create(items)
        if receive_people:
            obj.type = 'd'
        else:
            obj.type = 'e'
        obj.save()
        if str(message) == '1':
            message_str = f'上级来文：您有一份“{obj.recive_number}”“{obj.title}”的上级来文需要处理接收，请您在OA系统上查收。'
            send_mssage(mobile_list, message_str)
        returnDict = {'code': 200, 'message': '操作成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class OfficialDocumentsBackView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)
        audit_people = request.POST.get('audit_people', None)
        audit_people = re.findall('\((.*?)\)', audit_people)
        audit_people_objs = User.objects.filter(job_number__in=audit_people)
        obj = OfficialDocuments.objects.get(id=int(id))
        if obj.state == 'cancel':
            returnData = {'code': 500, 'message': '已经作废的单据，不能退回！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif state == 'i':
            obj.officialdocumentspeople_set.all().delete()
            obj.officialdocumentsauditrecord_set.all().delete()
            obj.current_audit_users.clear()
            obj.state='a'
            obj.type='a'
            obj.current_audit_users.add(obj.apply_user)
            obj.type = 'f'
            obj.save()
            if obj.public_search:
                public_search_obj = obj.public_search
                public_search_obj.audit_users_already.add(request.user)
                public_search_obj.current_audit_users.clear()
                for audit_user in obj.current_audit_users.all():
                    public_search_obj.current_audit_users.add(audit_user)
                public_search_obj.state = obj.state
                public_search_obj.save()
            returnData = {'code': 200, 'message': 'ok！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            if state == 'a':
                obj.officialdocumentspeople_set.all().delete()
                obj.officialdocumentsauditrecord_set.all().delete()
                obj.current_audit_users.clear()

                for audit_people_obj in audit_people_objs:
                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state='unaudit', audit_people=audit_people_obj, audit_note='', node='YB')
                    obj.current_audit_users.add(audit_people_obj)

                obj.type = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'b':
                if obj.type == 'a':
                    returnData = {'code': 500, 'message': '该流程未到达该节点！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

                obj.officialdocumentspeople_set.all().delete()
                obj.officialdocumentsauditrecord_set.filter(node__in=['YZ/SJ', 'B', "SQ"]).delete()
                obj.current_audit_users.clear()

                for audit_people_obj in audit_people_objs:
                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state='unaudit', audit_people=audit_people_obj, audit_note='', node='YZ/SJ')
                    obj.current_audit_users.add(audit_people_obj)

                obj.type = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'c':
                if obj.type in ['a', 'b']:
                    returnData = {'code': 500, 'message': '该流程未到达该节点！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                obj.officialdocumentspeople_set.all().delete()
                obj.officialdocumentsauditrecord_set.filter(node='B').delete()
                obj.current_audit_users.clear()
                for audit_people_obj in audit_people_objs:
                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state='unaudit', audit_people=audit_people_obj, audit_note='', node='B')
                    obj.current_audit_users.add(audit_people_obj)
                obj.type = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'f':
                obj.officialdocumentspeople_set.all().delete()
                obj.officialdocumentsauditrecord_set.all().delete()
                obj.current_audit_users.clear()
                dzb_director = Company.objects.get(id=3).head_people
                OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state='unaudit', node='YB', audit_note='', audit_people=dzb_director)
                obj.current_audit_users.add(obj.apply_user)
                obj.type = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            elif state == 'h':
                obj.officialdocumentspeople_set.all().delete()
                obj.officialdocumentsauditrecord_set.filter(node__in=['B', "SQ"]).delete()
                OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, audit_people=obj.apply_user, audit_note='', node='SQ')
                obj.current_audit_users.add(obj.apply_user)
                obj.type = state
                obj.save()
                returnData = {'code': 200, 'message': 'ok！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                returnData = {'code': 500, 'message': '请选择正确的状态！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")


class OfficialDocumentsCancelView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = OfficialDocuments.objects.get(id=int(id))
        if state == 'recall':
            if obj.officialdocumentsauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批上级来文才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            obj.current_audit_users.clear()
            obj.type = 'recall'
            obj.save()
        elif state == 'cancel':
            if obj.type != 'e':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的上级来文才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.type = 'cancel'
                obj.save()
        elif state == 'stop':
            if obj.type == 'e':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的上级来文不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.type = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '状态不正确！操作失败'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class OfficialDocumentsStopView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = OfficialDocuments.objects.get(id=int(id))
        # if obj.apply_user != request.user:
        #     returnData = {'code': 500, 'message': '终止失败！只有申请人才能终止流程'}
        #     return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_users.clear()
        obj.type = 'stop'
        obj.save()
        returnData = {'code': 200, 'message': '成功终止！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class OfficialDocumentsFinishView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = OfficialDocuments.objects.get(id=int(id))
        # if obj.apply_user != request.user:
        #     returnData = {'code': 500, 'message': '终止失败！只有申请人才能终止流程'}
        #     return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        obj.officialdocumentsauditrecord_set.filter(state='unaudit').delete()
        obj.type = 'e'
        obj.save()
        returnData = {'code': 200, 'message': '流程结束成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class OfficialDocumentsDetele(View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = OfficialDocuments.objects.get(id=int(id))
        recive_number = obj.recive_number.split('-')
        recive_num = int(recive_number[3])
        recive_date = datetime.datetime.strptime(recive_number[0] + '-' + recive_number[1] + '-' + recive_number[2], '%Y-%m-%d').date()
        tomorrow = recive_date + timedelta(days=1)
        official_documents_objs = OfficialDocuments.objects.filter(create_time__range=[recive_date, tomorrow])
        for official_documents_obj in official_documents_objs:
            official_documents_numbers = official_documents_obj.recive_number.split('-')
            if int(official_documents_numbers[3]) > recive_num:
                official_documents_numbers[3] = str(int(official_documents_numbers[3]) - 1)
                official_documents_numbers_str = '-'.join(official_documents_numbers)
                official_documents_obj.recive_number = official_documents_numbers_str
                official_documents_obj.save()
        obj.delete()
        returnData = {'code': 200, 'message': '删除！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


def fun1(sql_title, sql, sql_order, request, num1, num2, sql_count, where_tj, secrch_num=False):
    with connection.cursor() as cursor:
        if secrch_num:
            cursor.execute(sql_title + sql + sql_order, {f'{where_tj}': request.user.id, 'num1': num1, 'num2': num2, "audit_user_name": request.user.real_name})
            rows1 = cursor.fetchall()
            # cursor.execute(sql_count + sql, {f'{where_tj}': request.user.id, "audit_user_name": request.user.real_name})
            # rows1_num = cursor.fetchone()
        else:
            cursor.execute(sql_title + sql + sql_order, {f'{where_tj}': request.user.id, 'num1': num1, 'num2': num2, "audit_user_name": request.user.real_name})
            rows1 = cursor.fetchall()
            # cursor.execute(sql_count + sql, {f'{where_tj}': request.user.id})
            # rows1_num = cursor.fetchone()

        return rows1


class ProcessManagement(View):
    def get(self, request):
        page = request.GET.get('page', 1)
        page_type = request.GET.get('page_type', "0")
        # type 和 search_key 执行搜索方法时必须要传
        type = request.GET.get('type', 'apply')  # apply 查询我的申请 audit 查询我的待办 already 查询我的已办
        search_key = request.GET.get('search_key', None) # 要查询那一列
        search_value = request.GET.get('search_value', None) # 查询的内容
        '''
        search_key 为以下这些字段
        'classification','apply_user','company','state','audit_user','title'
        '''

        num1 = (int(page) - 1) * 20
        num2 = int(page) * 20
        sql_count = ''' SELECT count(*) as num '''
        sql_title = ''' SELECT * '''
        sql = ''' from (SELECT
            '车辆申请' as classification,
            a.id as id,
            a.create_time as create_time,
            u.real_name as apply_user,
            c.`name` as company,
                case when a.state = 'draft' then '审核中'
                 when a.state = 'fg' then '审核中'
                 when a.state = 'ybzr' then '审核中'
                 when a.state = 'cgb' then '完结'
                 when a.state = 'done' then '完结'
                 when a.state = 'refuse' then '退回'
                 when a.state = 'cancel' then '作废'
            END as state,
            au.real_name as audit_user,
            a.update_time as audit_time,
            a.`subject` as title,
            a.state as st
            from administrative_vehicleapply a
            INNER JOIN tb_users_message u on a.apply_user_id = u.id
            INNER JOIN administrative_company c on u.company_id = c.id
            LEFT JOIN tb_users_message au on au.id = a.current_audit_user_id
            where a.apply_user_id = %(apply_user)s
        union all
        
        SELECT
            '通知公告' as classification,
            u.id as id,
            u.create_time as create_time,
            c.real_name as apply_user,
            c.department as company,
            case when u.state = 'draft' then '审核中'
             when u.state = 'audit' then '完结'
             when u.state = 'unaudit' then '退回'
            END as state,
            au.real_name as audit_user,
            u.update_time as audit_time,
                        u.`name` as title,
                        u.state as st
            from  announcements_notice u 
            INNER JOIN tb_users_message c on u.create_people_id = c.id
            LEFT JOIN tb_users_message au on au.id = u.audit_people_id
            where u.create_people_id = %(apply_user)s
        union all
        
        SELECT
        (case when a.type = 'db' then '党委会议题'
                 when a.type = 'yb' then '院长办公会议题'
                 when a.type = 'xz' then '行政例会议题'
            END) as classification,
            a.id as id,
            a.create_time as create_time,
            u.real_name as apply_user,
            c.`name` as company,
            case when a.state = 'draft' then '审核中'
                 when a.state = 'confirm' then '审核中'
                 when a.state = 'audit' then '审核中'
                 when a.state = 'sj' then '审核中'
                 when a.state = 'done' then '完结'
                 when a.state = 'refuse' then '退回'
                 when a.state = 'cancel' then '作废'
            END as state,
            a.current_audit_user as audit_user,
            a.update_time as audit_time,
                    a.topics_name as title,
                    a.state as st
        FROM administrative_topics a
        INNER JOIN tb_users_message u on a.employee_id = u.id
        INNER JOIN administrative_company c on u.company_id = c.id
        where a.employee_id = %(apply_user)s
        
        union all
        
        SELECT
        (case when a.type = 'a' then '党委会议纪要'
                 when a.type = 'b' then '院长办公会会议纪要'
                 when a.type = 'c' then '党委专题会议纪要'
                 when a.type = 'd' then '院长办公会专题会议纪要'
                 when a.type = 'e' then '行政例会简报'
                 when a.type = 'f' then '行政公文(京医发)'
                 when a.type = 'g' then '党委公文'
                when a.type = 'h' then '行政公文(京医文)'
                END) as classification,
            a.id as id,
            a.create_time as create_time,
            u.real_name as apply_user,
            c.`name` as company,
            case when a.state = 'one' then '审核中'
                 when a.state = 'two' then '审核中'
                 when a.state = 'three' then '审核中'
                 when a.state = 'four' then '审核中'
                 when a.state = 'five' then '审核中'
                 when a.state = 'six' then '退回'
                 when a.state = 'seven' then '完结'
                 when a.state = 'eight' then '待分发'
                 when a.state = 'nine' then '审核中'
                 when a.state = 'stop' then '终止'
            END as state,
            GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
        a.update_time as audit_time,
                a.conference_memo_text as title,
                a.state as st
        FROM administrative_conferencememo a
        INNER JOIN tb_users_message u on a.apply_user_id = u.id
        INNER JOIN administrative_company c on u.company_id = c.id
        left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id
        LEFT JOIN tb_users_message au on m.user_id = au.id
        where a.apply_user_id = %(apply_user)s
        GROUP BY classification, id, create_time, apply_user, company, state
        
        union all
        
        SELECT
        '上级来文' as classification,
        a.id as id,
        a.create_time as create_time,
        u.real_name as apply_user, 
        c.`name` as company,
        case when a.type = 'a' then '审核中'
                 when a.type = 'b' then '审核中'
                 when a.type = 'c' then '审核中'
                 when a.type = 'h' then '审核中'
                 when a.type = 'd' then '传阅中'
                 when a.type = 'e' then '完结'
                 when a.type = 'f' then '退回'
                 when a.type = 'g' then '待分发'
                 when a.type = 'stop' then '终止'
            END as state,
        GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
        a.update_time as audit_time,
                a.title as title,
                a.state as st
        FROM administrative_officialdocuments a
        INNER JOIN tb_users_message u on a.apply_user_id = u.id
        INNER JOIN administrative_company c on u.company_id = c.id
        left join administrative_officialdocuments_current_audit_users m on m.officialdocuments_id = a.id
        LEFT JOIN tb_users_message au on m.user_id = au.id
        where a.apply_user_id = %(apply_user)s
        GROUP BY classification, id, create_time, apply_user, company, state, st
        
        union all
        
        SELECT
            '用印申请' as classification,
                a.id as id,
                a.create_time as create_time,
                u.real_name as apply_user, 
                c.`name` as company,
                case when a.state = 'five' then '完结'
                        when a.state = 'six' then '退回'
                        else '审核中'
                        END as state,
                GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                a.update_time as audit_time,
                a.matter_type_text as title,
                a.state as st
            
            from personal_center_sealapply a
            INNER JOIN tb_users_message u on a.apply_user_id = u.id
            INNER JOIN administrative_company c on u.company_id = c.id
            left join personal_center_sealapply_current_audit_users m on m.sealapply_id = a.id
            LEFT JOIN tb_users_message au on m.user_id = au.id
            where a.apply_user_id = %(apply_user)s
            GROUP BY classification, id, create_time, apply_user, company, state, st
            
            union all
            
            select
                b.module   as classification,
                a.id as id,
                a.create_time as create_time,
                u.real_name as apply_user, 
                c.`name` as company,
                case when a.state = 'two' then '完结'
                                when a.state = 'three' then '作废'
                                when a.state = 'four' then '退回'
                                else '审核中'
                                END as state,
                GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                a.update_time as audit_time,
                b.name as title,
                a.state as st
            
            from system_setup_lowcodebill a
            left join system_setup_customerform b on a.customer_form_id = b.id
            left join tb_users_message u on u.id = a.apply_user_id
            left join administrative_company c on u.company_id = c.id
            left join system_setup_lowcodebill_current_audit_users m on m.lowcodebill_id = a.id
            LEFT JOIN tb_users_message au on au.id = m.user_id
            where a.apply_user_id = %(apply_user)s
            GROUP BY classification, id, create_time, apply_user, company, state, st
            
            union all
            
            SELECT
                '医德医风考评'   as classification,
                a.id as id,
                a.create_time as create_time,
                u.real_name as apply_user, 
                c.`name` as company,
                case when a.state = 'five' then '完结'
                                                else '审核中'
                                                END as state,
                GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                a.update_time as audit_time,
                a.title as title,
                a.state as st
                
                from medical_ethics_evaluationofmedicalethics a
                left join tb_users_message u on u.id = a.apply_user_id
                left join administrative_company c on a.apply_company_id = c.id
                left join medical_ethics_evaluationofmedicalethics_current_audit_users m on m.evaluationofmedicalethics_id = a.id
                left join tb_users_message au on au.id = m.user_id
                where a.apply_user_id = %(apply_user)s
                GROUP BY classification, id, create_time, apply_user, company, state, st
                
                union all
            
                SELECT 
                    '会议室申请'   as classification,
                    a.id as id,
                    a.create_time as create_time,
                    a.names as apply_user, 
                    a.department as company,
                    case when a.state = 'audit' then '完结'
                    when a.state = 'revoke' then '撤销'
                                                    else '审核中'
                                                    END as state,
                    u.real_name as audit_user,
                    a.update_time as audit_time,
                    a.meeting_root as title,
                    a.state as st

                    FROM personal_center_conferenceroomapplication a
                    left join tb_users_message u on a.audit_people_id = u.id
                    where a.names = %(audit_user_name)s
                    GROUP BY classification, id, create_time, apply_user, company, state, st
        
        ) base where 1=1 '''
        if type == 'apply':
            if search_key == 'classification':
                sql += ''' and base.classification like ''' + ''' '%%{}%%' '''.format(search_value)
            if search_key == 'apply_user':
                sql += ''' and base.apply_user like ''' + ''' '%%{}%%' '''.format(search_value)
            if search_key == 'company':
                sql += ''' and base.company like ''' + ''' '%%{}%%' '''.format(search_value)
            if search_key == 'state':
                sql += ''' and base.state = '%s' ''' % search_value
            if search_key == 'audit_user':
                # search_value = '%' + search_value + '%'
                sql += ''' and base.audit_user like ''' + ''' '%%{}%%' '''.format(search_value)
            if search_key == 'title':
                sql += ''' and base.title like ''' + ''' '%%{}%%' '''.format(search_value)
        sql_order = ''' ORDER BY create_time desc
                '''
        sql2_count = ''' SELECT count(*) as num '''
        sql2_title = ''' SELECT * '''
        sql2 = '''
                    from (SELECT
                        '车辆申请' as classification,
                    a.id as id,
                    a.create_time as create_time,
                    u.real_name as apply_user,
                    c.`name` as company,
                        case when a.state = 'draft' then '审核中'
                         when a.state = 'fg' then '审核中'
                         when a.state = 'ybzr' then '审核中'
                         when a.state = 'cgb' then '完结'
                         when a.state = 'done' then '完结'
                         when a.state = 'refuse' then '退回'
                         when a.state = 'cancel' then '作废'
                    END as state,
                    au.real_name as audit_user,
                    a.update_time as audit_time,
                    a.`subject` as title
                    from administrative_vehicleapply a
                    INNER JOIN tb_users_message u on a.apply_user_id = u.id
                    INNER JOIN administrative_company c on u.company_id = c.id
                    LEFT JOIN tb_users_message au on au.id = a.current_audit_user_id
                    where a.current_audit_user_id = %(audit_user)s
                union all
                
                SELECT
                '通知公告' as classification,
                u.id as id,
                A.create_time as create_time,
                c.real_name as apply_user,
                c.department as company,
                                case when A.state = 'draft' then '退回'
                                 when A.state = 'audit' then '完结'
                                 when A.state = 'unaudit' then '审核中'
                        END as state,
                        au.real_name as audit_user,
                        u.update_time as audit_time,
                        u.`name` as title
                        from announcements_auditrecord	A
                        INNER JOIN announcements_notice u on A.notice_id_id = u.id
                        INNER JOIN tb_users_message c on u.create_people_id = c.id
                        LEFT JOIN tb_users_message au on au.id = u.audit_people_id
                        where u.audit_people_id = %(audit_user)s AND A.state='unaudit'
                union all

                SELECT
                (case when a.type = 'db' then '党委会议题'
                 when a.type = 'yb' then '院长办公会议题'
                 when a.type = 'xz' then '行政例会议题'
            END) as classification,
                    a.id as id,
                    a.create_time as create_time,
                    u.real_name as apply_user,
                    c.`name` as company,
                    case when a.state = 'draft' then '审核中'
                         when a.state = 'confirm' then '审核中'
                         when a.state = 'audit' then '审核中'
                         when a.state = 'sj' then '审核中'
                         when a.state = 'done' then '完结'
                         when a.state = 'refuse' then '退回'
                         when a.state = 'cancel' then '作废'
                         when a.state = 'stop' then '终止'
                         
                    END as state,
                    a.current_audit_user as audit_user,
                    a.update_time as audit_time,
                    a.topics_name as title
                FROM administrative_topics a
                INNER JOIN tb_users_message u on a.employee_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                where a.current_audit_user = %(audit_user_name)s

                union all

                SELECT
                (case when a.type = 'a' then '党委会议纪要'
                 when a.type = 'b' then '院长办公会会议纪要'
                 when a.type = 'c' then '党委专题会议纪要'
                 when a.type = 'd' then '院长办公会专题会议纪要'
                 when a.type = 'e' then '行政例会简报'
                 when a.type = 'f' then '行政公文(京医发)'
                 when a.type = 'g' then '党委公文'
								 when a.type = 'h' then '行政公文(京医文)'
            END) as classification,
                    a.id as id,
                    a.create_time as create_time,
                    u.real_name as apply_user,
                    c.`name` as company,
                    case when a.state = 'one' then '审核中'
                         when a.state = 'two' then '审核中'
                         when a.state = 'three' then '审核中'
                         when a.state = 'four' then '审核中'
                         when a.state = 'five' then '审核中'
                         when a.state = 'six' then '退回'
                         when a.state = 'seven' then '完结'
                         when a.state = 'eight' then '待分发'
                         when a.state = 'nine' then '审核中'
                         when a.state = 'stop' then '终止'
                    END as state,
                    GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                    a.update_time as audit_time,
                    a.conference_memo_text as title
                FROM administrative_conferencememo a
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id
                LEFT JOIN tb_users_message au on m.user_id = au.id
                where au.id = %(audit_user)s
                GROUP BY classification, id, create_time, apply_user, company, state

                union all
                
                SELECT
                (case when a.type = 'a' then '党委会议纪要(收阅)'
                 when a.type = 'b' then '院长办公会会议纪要(收阅)'
                 when a.type = 'c' then '党委专题会议纪要(收阅)'
                 when a.type = 'd' then '院长办公会专题会议纪要(收阅)'
                 when a.type = 'e' then '行政例会简报(收阅)'
                 when a.type = 'f' then '京医发(收阅)'
                 when a.type = 'g' then '党委公文(收阅)'
								 when a.type = 'h' then '京医文(收阅)'
            END) as classification,
                    a.id as id,
                    a.create_time as create_time,
                    u.real_name as apply_user,
                    c.`name` as company,
                    '传阅中' as state,
                    '' as audit_user,
                    a.update_time as audit_time,
                    a.conference_memo_text as title
                FROM administrative_conferencememo a
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join administrative_conferencememopeople m on m.notice_id_id = a.id
                LEFT JOIN tb_users_message au on m.audit_people_id = au.id
                where au.id = %(audit_user)s AND m.state='accept'
                GROUP BY classification, id, create_time, apply_user, company, state

                union all
								
								SELECT
                '上级来文(收阅)' as classification,
                a.id as id,
                a.create_time as create_time,
                u.real_name as apply_user,
                c.`name` as company,
                '传阅中' as state,
                '' as audit_user,
                a.update_time as audit_time,
                a.title as title
                FROM administrative_officialdocuments a
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join administrative_officialdocumentspeople m on m.notice_id_id = a.id
                LEFT JOIN tb_users_message au on m.audit_people_id = au.id
                where au.id = %(audit_user)s AND m.state='accept'
                GROUP BY classification, id, create_time, apply_user, company, state
								
								union all

                SELECT
                '上级来文' as classification,
                a.id as id,
                a.create_time as create_time,
                u.real_name as apply_user,
                c.`name` as company,
                case when a.type = 'a' then '审核中'
                         when a.type = 'b' then '审核中'
                         when a.type = 'c' then '审核中'
                         when a.type = 'h' then '审核中'
                         when a.type = 'd' then '传阅中'
                         when a.type = 'e' then '完结'
                         when a.type = 'f' then '退回'
                         when a.type = 'g' then '待分发'
                    END as state,
                GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                a.update_time as audit_time,
                a.title as title
                FROM administrative_officialdocuments a
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join administrative_officialdocuments_current_audit_users m on m.officialdocuments_id = a.id
                LEFT JOIN tb_users_message au on m.user_id = au.id
                where au.id = %(audit_user)s
                GROUP BY classification, id, create_time, apply_user, company, state
                
                union all
                
                SELECT
                '用印申请' as classification,
                    a.id as id,
                    a.create_time as create_time,
                    u.real_name as apply_user, 
                    c.`name` as company,
                    case when a.state = 'five' then '完结'
                            when a.state = 'six' then '退回'
                            else '审核中'
                            END as state,
                    GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                    a.update_time as audit_time,
                    a.matter_type_text as title
                
                from personal_center_sealapply a
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join personal_center_sealapply_current_audit_users m on m.sealapply_id = a.id
                LEFT JOIN tb_users_message au on m.user_id = au.id
                where au.id = %(audit_user)s
                GROUP BY classification, id, create_time, apply_user, company, state
                
                union all 
                
                SELECT
                b.module   as classification,
                a.id as id,
                a.create_time as create_time,
                u.real_name as apply_user, 
                c.`name` as company,
                case when a.state = 'two' then '完结'
                                when a.state = 'three' then '作废'
                                when a.state = 'four' then '退回'
                                else '审核中'
                                END as state,
                GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                a.update_time as audit_time,
                b.name as title
                from system_setup_lowcodebill a
                left join system_setup_customerform b on a.customer_form_id = b.id
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join system_setup_lowcodebill_current_audit_users m on m.lowcodebill_id = a.id
                LEFT JOIN tb_users_message au on m.user_id = au.id
                where au.id = %(audit_user)s
                GROUP BY classification, id, create_time, apply_user, company, state
                
                union all 
                
                SELECT
                '医德医风考评'   as classification,
                a.id as id,
                a.create_time as create_time,
                u.real_name as apply_user, 
                c.`name` as company,
                case when a.state = 'five' then '完结'
                                                else '审核中'
                                                END as state,
                GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                a.update_time as audit_time,
                a.title as title
                
                from medical_ethics_evaluationofmedicalethics a
                left join tb_users_message u on u.id = a.apply_user_id
                left join administrative_company c on a.apply_company_id = c.id
                left join medical_ethics_evaluationofmedicalethics_current_audit_users m on m.evaluationofmedicalethics_id = a.id
                left join tb_users_message au on au.id = m.user_id
                where au.id = %(audit_user)s
                GROUP BY classification, id, create_time, apply_user, company, state
                
                union all 
                
                SELECT 
                    '会议室申请'   as classification,
                    a.id as id,
                    a.create_time as create_time,
                    a.names as apply_user, 
                    a.department as company,
                    case when a.state = 'audit' then '完结'
                    when a.state = 'revoke' then '撤销'
                                                    else '审核中'
                                                    END as state,
                    u.real_name as audit_user,
                    a.update_time as audit_time,
                    a.meeting_root as title

                    FROM personal_center_conferenceroomapplication a
                    left join tb_users_message u on a.audit_people_id = u.id
                    where a.audit_people_id = %(audit_user)s
                    GROUP BY classification, id, create_time, apply_user, company, state
                
                ) base where 1=1 '''
        if type == 'audit':
            if search_key == 'classification':
                sql2 += ''' and base.classification like ''' + ''' '%%{}%%' '''.format(search_value)
            if search_key == 'apply_user':
                sql2 += ''' and base.apply_user like ''' + ''' '%%{}%%' '''.format(search_value)
            if search_key == 'company':
                sql2 += ''' and base.company like ''' + ''' '%%{}%%' '''.format(search_value)
            if search_key == 'state':
                sql2 += ''' and base.state = '%s' ''' % search_value
            if search_key == 'audit_user':
                # search_value = '%' + search_value + '%'
                sql2 += ''' and base.audit_user like ''' + ''' '%%{}%%' '''.format(search_value)
            if search_key == 'title':
                sql2 += ''' and base.title like ''' + ''' '%%{}%%' '''.format(search_value)
        sql2_order = '''ORDER BY create_time desc'''

        sql3_count = ''' SELECT count(*) as num '''
        sql3_title = ''' SELECT * '''
        sql3 = '''
                     from (SELECT
                    '车辆申请' as classification,
                    a.id as id,
                    a.create_time as create_time,
                    u.real_name as apply_user,
                    c.`name` as company,
                        case when a.state = 'draft' then '审核中'
                         when a.state = 'fg' then '审核中'
                         when a.state = 'ybzr' then '审核中'
                         when a.state = 'cgb' then '完结'
                         when a.state = 'done' then '完结'
                         when a.state = 'refuse' then '退回'
                         when a.state = 'cancel' then '作废'
                    END as state,
                    au.real_name as audit_user,
                    a.update_time as audit_time,
                    a.`subject` as title
                    from administrative_vehicleapply a
                    INNER JOIN tb_users_message u on a.apply_user_id = u.id
                    INNER JOIN administrative_company c on u.company_id = c.id
                    LEFT JOIN tb_users_message au on au.id = a.current_audit_user_id
                    LEFT JOIN administrative_vehicleapply_already_users am on am.vehicleapply_id = a.id
	                left join tb_users_message already_user on already_user.id = am.user_id
                    where already_user.id = %(already_users)s
                union all
                
                SELECT
                '通知公告' as classification,
                u.id as id, 
                u.create_time as create_time, 
                c.real_name as apply_user, 
                c.department as company, 
                case when A.state = 'draft' then '退回' 
                when A.state = 'audit' then '完结' 
                when A.state = 'unaudit' then '审核中' 
                END as state, 
                au.real_name as audit_user, 
                u.update_time as audit_time, 
                u.`name` as title 
                from announcements_auditrecord	A 
                LEFT JOIN announcements_notice u on A.notice_id_id = u.id 
                LEFT JOIN tb_users_message c on u.create_people_id = c.id 
                LEFT JOIN tb_users_message au on au.id = u.audit_people_id
                        where A.audit_people_id = %(already_users)s AND A.state in ('audit', 'draft')
                union all

                SELECT
                (case when a.type = 'db' then '党委会议题'
                 when a.type = 'yb' then '院长办公会议题'
                 when a.type = 'xz' then '行政例会议题'
            END) as classification,
                    a.id as id,
                    a.create_time as create_time,
                    u.real_name as apply_user,
                    c.`name` as company,
                    case when a.state = 'draft' then '审核中'
                         when a.state = 'confirm' then '审核中'
                         when a.state = 'audit' then '审核中'
                         when a.state = 'sj' then '审核中'
                         when a.state = 'done' then '完结'
                         when a.state = 'refuse' then '退回'
                         when a.state = 'cancel' then '作废'
                         when a.state = 'stop' then '终止'
                    END as state,
                    a.current_audit_user as audit_user,
                    a.update_time as audit_time,
                    a.topics_name as title
                FROM administrative_topics a
                INNER JOIN tb_users_message u on a.employee_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                LEFT JOIN administrative_topics_already_users am on am.topics_id = a.id
                left join tb_users_message already_user on already_user.id = am.user_id
                where already_user.id = %(already_users)s

                union all

                SELECT
                (case when a.type = 'a' then '党委会议纪要'
                 when a.type = 'b' then '院长办公会会议纪要'
                 when a.type = 'c' then '党委专题会议纪要'
                 when a.type = 'd' then '院长办公会专题会议纪要'
                 when a.type = 'e' then '行政例会简报'
                 when a.type = 'f' then '行政公文(京医发)'
                 when a.type = 'g' then '党委公文'
								 when a.type = 'h' then '行政公文(京医文)'
            END) as classification,
                    a.id as id,
                    a.create_time as create_time,
                    u.real_name as apply_user,
                    c.`name` as company,
                    case when a.state = 'one' then '审核中'
                             when a.state = 'two' then '审核中'
                             when a.state = 'three' then '审核中'
                             when a.state = 'four' then '审核中'
                             when a.state = 'five' then '审核中'
                             when a.state = 'six' then '退回'
                             when a.state = 'seven' then '完结'
                             when a.state = 'eight' then '待分发'
                             when a.state = 'nine' then '审核中'
                             when a.state = 'stop' then '终止'
                    END as state,
                    GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                    a.update_time as audit_time,
                    a.conference_memo_text as title
                FROM administrative_conferencememo a
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id
                LEFT JOIN tb_users_message au on m.user_id = au.id
                LEFT JOIN administrative_conferencememo_audit_users_already am on am.conferencememo_id = a.id
                left join tb_users_message already_user on already_user.id = am.user_id
                where already_user.id = %(already_users)s

                GROUP BY classification, id, create_time, apply_user, company, state

                union all

                SELECT
                '上级来文' as classification,
                a.id as id,
                a.create_time as create_time,
                u.real_name as apply_user,
                c.`name` as company,
                case when a.type = 'a' then '审核中'
                         when a.type = 'b' then '审核中'
                         when a.type = 'c' then '审核中'
                         when a.type = 'h' then '审核中'
                         when a.type = 'd' then '传阅中'
                         when a.type = 'e' then '完结'
                         when a.type = 'f' then '退回'
                         when a.type = 'g' then '待分发'
                         when a.type = 'stop' then '终止'
                    END as state,
                GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                a.update_time as audit_time,
                a.title as title
                FROM administrative_officialdocuments a
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join administrative_officialdocuments_current_audit_users m on m.officialdocuments_id = a.id
                LEFT JOIN tb_users_message au on m.user_id = au.id
                LEFT JOIN administrative_officialdocuments_audit_users_already am on am.officialdocuments_id = a.id
                left join tb_users_message already_user on already_user.id = am.user_id
                where already_user.id = %(already_users)s
                GROUP BY classification, id, create_time, apply_user, company, state
                
                union all
                
                SELECT
                '用印申请' as classification,
                    a.id as id,
                    a.create_time as create_time,
                    u.real_name as apply_user, 
                    c.`name` as company,
                    case when a.state = 'five' then '完结'
                            when a.state = 'six' then '退回'
                            else '审核中'
                            END as state,
                    GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                    a.update_time as audit_time,
                    a.matter_type_text as title
                
                from personal_center_sealapply a
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join personal_center_sealapply_current_audit_users m on m.sealapply_id = a.id
                LEFT JOIN tb_users_message au on m.user_id = au.id
                LEFT JOIN personal_center_sealapply_audit_users_already am on am.sealapply_id = a.id
                left join tb_users_message already_user on already_user.id = am.user_id
                where already_user.id = %(already_users)s
                GROUP BY classification, id, create_time, apply_user, company, state
                
                union all
                
                SELECT
                b.module   as classification,
                a.id as id,
                a.create_time as create_time,
                u.real_name as apply_user, 
                c.`name` as company,
                case when a.state = 'two' then '完结'
                                when a.state = 'three' then '作废'
                                when a.state = 'four' then '退回'
                                else '审核中'
                                END as state,
                GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                a.update_time as audit_time,
                b.name as title
                
                from system_setup_lowcodebill a
                left join system_setup_customerform b on a.customer_form_id = b.id
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join system_setup_lowcodebill_current_audit_users m on m.lowcodebill_id = a.id
                LEFT JOIN tb_users_message au on m.user_id = au.id
                LEFT JOIN system_setup_lowcodebill_audit_users_already am on am.lowcodebill_id = a.id
                left join tb_users_message already_user on already_user.id = am.user_id
                where already_user.id = %(already_users)s
                GROUP BY classification, id, create_time, apply_user, company, state
                
                union all 
                
                SELECT
                '医德医风考评'   as classification,
                a.id as id,
                a.create_time as create_time,
                u.real_name as apply_user, 
                c.`name` as company,
                case when a.state = 'five' then '完结'
                                                else '审核中'
                                                END as state,
                GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user,
                a.update_time as audit_time,
                a.title as title
                
                from medical_ethics_evaluationofmedicalethics a
                left join tb_users_message u on u.id = a.apply_user_id
                left join administrative_company c on a.apply_company_id = c.id
                left join medical_ethics_evaluationofmedicalethics_current_audit_users m on m.evaluationofmedicalethics_id = a.id
                left join tb_users_message au on au.id = m.user_id
                left join medical_ethics_evaluationofmedicalethics_audit_users_already am on am.evaluationofmedicalethics_id = a.id
                left join tb_users_message already_user on already_user.id = am.user_id
                
                where already_user.id = %(already_users)s
                GROUP BY classification, id, create_time, apply_user, company, state
                
                union all 
                
                SELECT 
                    '会议室申请'   as classification,
                    a.id as id,
                    a.create_time as create_time,
                    a.names as apply_user, 
                    a.department as company,
                    case when a.state = 'audit' then '完结'
                    when a.state = 'revoke' then '撤销'
                                                    else '审核中'
                                                    END as state,
                    u.real_name as audit_user,
                    a.update_time as audit_time,
                    a.meeting_root as title

                    FROM personal_center_conferenceroomapplication a
                    left join tb_users_message u on a.audit_people_id = u.id
                    left join personal_center_conferenceroomapplication_audit_users_already am on am.conferenceroomapplication_id = a.id
                    left join tb_users_message already_user on already_user.id = am.user_id 
                    where already_user.id = %(already_users)s
                    GROUP BY classification, id, create_time, apply_user, company, state
                
                ) base where 1=1 '''
        if type == 'already':
            if search_key == 'classification':
                sql3 += ''' and base.classification like ''' + ''' '%%{}%%' '''.format(search_value)
            if search_key == 'apply_user':
                sql3 += ''' and base.apply_user like ''' + ''' '%%{}%%' '''.format(search_value)
            if search_key == 'company':
                sql3 += ''' and base.company like ''' + ''' '%%{}%%' '''.format(search_value)
            if search_key == 'state':
                sql3 += ''' and base.state = '%s' ''' % search_value
            if search_key == 'audit_user':
                sql3 += ''' and base.audit_user like ''' + ''' '%%{}%%' '''.format(search_value)
            if search_key == 'title':
                sql3 += ''' and base.title like ''' + ''' '%%{}%%' '''.format(search_value)
        sql3_order = ''' ORDER BY create_time desc'''

        data1 = []
        data2 = []
        data3 = []
        shenqing_list, daiban_list, yiban_list = [], [], []
        a, b, c, d, e, f = [], [], [], [], [], []
        a1, b1, c1, d1, e1, f1 = [], [], [], [], [], []
        a2, b2, c2, d2, e2, f2 = [], [], [], [], [], []
        if page_type == "0":
            rows1 = fun1(sql_title, sql, sql_order, request, num1, num2, sql_count, "apply_user")
            rows2 = fun1(sql2_title, sql2, sql2_order, request, num1, num2, sql2_count, "audit_user", secrch_num=True)
            rows3 = fun1(sql3_title, sql3, sql3_order, request, num1, num2, sql3_count, "already_users")
            for row in rows1:
                row_dict = {
                    'classification': row[0],
                    'id': row[1],
                    'create_time': row[2].strftime("%Y-%m-%d %H:%M"),
                    'apply_user': row[3],
                    'company': row[4],
                    'state': row[5],
                    'audit_user': row[6],
                    'title': row[8],
                    'st': row[9],
                    'audit_time': row[7].strftime("%Y-%m-%d %H:%M")
                }
                if row[5] == "审核中":
                    a1.append(row_dict)
                elif row[5] == "待分发":
                    b1.append(row_dict)
                elif row[5] == "传阅中":
                    c1.append(row_dict)
                elif row[5] == "退回":
                    e1.append(row_dict)
                elif row[5] == "作废":
                    f1.append(row_dict)
                else:
                    d1.append(row_dict)
                data1 = a1 + b1 + c1 + e1 + f1 + d1
                if row[0] not in shenqing_list:
                    shenqing_list.append(row[0])
            for row in rows2:
                row_dict = {
                    'classification': row[0],
                    'id': row[1],
                    'title': row[8],
                    'create_time': row[2].strftime("%Y-%m-%d %H:%M"),
                    'apply_user': row[3],
                    'company': row[4],
                    'state': row[5],
                    'audit_user': row[6],
                    'audit_time': row[7].strftime("%Y-%m-%d %H:%M")
                }
                if row[5] == "审核中":
                    a.append(row_dict)
                elif row[5] == "待分发":
                    b.append(row_dict)
                elif row[5] == "传阅中":
                    c.append(row_dict)
                elif row[5] == "退回":
                    e.append(row_dict)
                elif row[5] == "作废":
                    f.append(row_dict)
                else:
                    d.append(row_dict)
                data2 = a + e + b + c + f + d
                if row[0] not in daiban_list:
                    daiban_list.append(row[0])
            for row in rows3:
                row_dict = {
                    'classification': row[0],
                    'id': row[1],
                    'create_time': row[2].strftime("%Y-%m-%d %H:%M"),
                    'apply_user': row[3],
                    'company': row[4],
                    'state': row[5],
                    'audit_user': row[6],
                    'title': row[8],
                    'audit_time': row[7].strftime("%Y-%m-%d %H:%M")
                }
                if row[5] == "审核中":
                    a2.append(row_dict)
                elif row[5] == "待分发":
                    b2.append(row_dict)
                elif row[5] == "传阅中":
                    c2.append(row_dict)
                elif row[5] == "退回":
                    e2.append(row_dict)
                elif row[5] == "作废":
                    f2.append(row_dict)
                else:
                    d2.append(row_dict)
                data3 = a2 + b2 + c2 + e2 + f2 + d2
                if row[0] not in yiban_list:
                    yiban_list.append(row[0])
        elif page_type == "1":
            rows1 = fun1(sql_title, sql, sql_order, request, num1, num2, sql_count, "apply_user")
            for row in rows1:
                row_dict = {
                    'classification': row[0],
                    'id': row[1],
                    'create_time': row[2].strftime("%Y-%m-%d %H:%M"),
                    'apply_user': row[3],
                    'company': row[4],
                    'state': row[5],
                    'audit_user': row[6],
                    'title': row[8],
                    'st': row[9],
                    'audit_time': row[7].strftime("%Y-%m-%d %H:%M")
                }
                if row[5] == "审核中":
                    a1.append(row_dict)
                elif row[5] == "待分发":
                    b1.append(row_dict)
                elif row[5] == "传阅中":
                    c1.append(row_dict)
                elif row[5] == "退回":
                    e1.append(row_dict)
                elif row[5] == "作废":
                    f1.append(row_dict)
                else:
                    d1.append(row_dict)
                data1 = a1 + b1 + c1 + e1 + f1 + d1
                if row[0] not in shenqing_list:
                    shenqing_list.append(row[0])
        elif page_type == "2":
            rows2 = fun1(sql2_title, sql2, sql2_order, request, num1, num2, sql2_count, "audit_user", secrch_num=True)
            for row in rows2:
                row_dict = {
                    'classification': row[0],
                    'id': row[1],
                    'title': row[8],
                    'create_time': row[2].strftime("%Y-%m-%d %H:%M"),
                    'apply_user': row[3],
                    'company': row[4],
                    'state': row[5],
                    'audit_user': row[6],
                    'audit_time': row[7].strftime("%Y-%m-%d %H:%M")
                }
                if row[5] == "审核中":
                    a.append(row_dict)
                elif row[5] == "待分发":
                    b.append(row_dict)
                elif row[5] == "传阅中":
                    c.append(row_dict)
                elif row[5] == "退回":
                    e.append(row_dict)
                elif row[5] == "作废":
                    f.append(row_dict)
                else:
                    d.append(row_dict)
                data2 = a + e + b + c + f + d
                if row[0] not in daiban_list:
                    daiban_list.append(row[0])
        else:
            rows3 = fun1(sql3_title, sql3, sql3_order, request, num1, num2, sql3_count, "already_users")
            for row in rows3:
                row_dict = {
                    'classification': row[0],
                    'id': row[1],
                    'create_time': row[2].strftime("%Y-%m-%d %H:%M"),
                    'apply_user': row[3],
                    'company': row[4],
                    'state': row[5],
                    'audit_user': "" if row[0] == "通知公告" and row[5] != "unaudit" else row[6],
                    'title': row[8],
                    'audit_time': row[7].strftime("%Y-%m-%d %H:%M")
                }
                if row[5] == "审核中":
                    a2.append(row_dict)
                elif row[5] == "待分发":
                    b2.append(row_dict)
                elif row[5] == "传阅中":
                    c2.append(row_dict)
                elif row[5] == "退回":
                    e2.append(row_dict)
                elif row[5] == "作废":
                    f2.append(row_dict)
                else:
                    d2.append(row_dict)
                data3 = a2 + b2 + c2 + e2 + f2 + d2
                if row[0] not in yiban_list:
                    yiban_list.append(row[0])

        returnDict = {'code': 200, 'message': '操作成功', 'my_apply_list': data1[num1:num2], 'my_audit_list': data2[num1:num2], 'my_already_list': data3[num1:num2], "daiban_list": daiban_list, "yiban_list": yiban_list, "shenqing_list": shenqing_list, 'my_apply_list_count': len(data1), 'my_audit_list_count': len(data2), 'my_already_list_count': len(data3)}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GetBacklogView(View):
    def get(self, request):
        sql = '''
        SELECT count(id) as num from (
        SELECT '车辆申请' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'fg' then '审核中' when a.state = 'ybzr' then '审核中' when a.state = 'cgb' then '完结' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' END as state, au.real_name as audit_user, a.update_time as audit_time, a.`subject` as title from administrative_vehicleapply a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id LEFT JOIN tb_users_message au on au.id = a.current_audit_user_id where a.current_audit_user_id = %(audit_user)s
        union all
        SELECT '通知公告' AS classification, A.id AS id, A.id AS create_time, c.real_name AS apply_user, c.department AS company, CASE WHEN u.state = 'eight' THEN '退回' WHEN u.state = 'eight' THEN '完结' WHEN u.state = 'eight' THEN '审核中' END AS state, au.real_name AS audit_user, u.update_time AS audit_time, u.`name` AS title FROM announcements_notice_current_audit_users A INNER JOIN announcements_notice u ON A.notice_id = u.id INNER JOIN tb_users_message c ON u.create_people_id = c.id LEFT JOIN tb_users_message au ON au.id = A.user_id WHERE A.user_id = %(audit_user)s AND u.state IN ( 'one', 'two', 'eight')
        union all
        SELECT (case when a.type = 'db' then '党委会议题' when a.type = 'yb' then '院长办公会议题' when a.type = 'xz' then '行政例会议题' END) as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'draft' then '审核中' when a.state = 'confirm' then '审核中' when a.state = 'audit' then '审核中' when a.state = 'sj' then '审核中' when a.state = 'done' then '完结' when a.state = 'refuse' then '退回' when a.state = 'cancel' then '作废' when a.state = 'stop' then '终止' END as state, a.current_audit_user as audit_user, a.update_time as audit_time, a.topics_name as title FROM administrative_topics a INNER JOIN tb_users_message u on a.employee_id = u.id INNER JOIN administrative_company c on u.company_id = c.id where a.current_audit_user = %(audit_user_name)s AND a.state != 'shelve'
        union all
        SELECT (case when a.type = 'a' then '党委会议纪要' when a.type = 'b' then '院长办公会会议纪要' when a.type = 'c' then '党委专题会议纪要' when a.type = 'd' then '院长办公会专题会议纪要' when a.type = 'e' then '行政例会简报' when a.type = 'f' then '行政公文(京医发)' when a.type = 'g' then '党委公文' when a.type = 'h' then '行政公文(京医文)' END) as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'one' then '审核中' when a.state = 'two' then '审核中' when a.state = 'three' then '审核中' when a.state = 'four' then '审核中' when a.state = 'five' then '审核中' when a.state = 'six' then '退回' when a.state = 'seven' then '完结' when a.state = 'eight' then '待分发' when a.state = 'nine' then '审核中' when a.state = 'stop' then '终止' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.conference_memo_text as title FROM administrative_conferencememo a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_conferencememo_current_audit_users m on m.conferencememo_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where au.id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '上级来文' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.type = 'a' then '审核中' when a.type = 'b' then '审核中' when a.type = 'c' then '审核中' when a.type = 'h' then '审核中' when a.type = 'd' then '传阅中' when a.type = 'e' then '完结' when a.type = 'f' then '退回' when a.type = 'g' then '待分发' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.title as title FROM administrative_officialdocuments a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_officialdocuments_current_audit_users m on m.officialdocuments_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where au.id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '外部来函' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.type = 'one' then '审核中' when a.type = 'two' then '审核中' when a.type = 'three' then '审核中' when a.type = 'eight' then '审核中' when a.type = 'four' then '传阅中' when a.type = 'five' then '完结' when a.type = 'six' then '退回' when a.type = 'seven' then '待分发' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.title as title FROM administrative_correspondence a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_correspondence_current_audit_users m on m.correspondence_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where au.id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '用印申请' as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'five' then '完结' when a.state = 'six' then '退回' else '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.matter_type_text as title from personal_center_sealapply a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join personal_center_sealapply_current_audit_users m on m.sealapply_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where au.id = %(audit_user)s and a.state!='shelve' GROUP BY classification, id, create_time, apply_user, company, state
        union all 
        SELECT b.module   as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'two' then '完结' when a.state = 'three' then '作废' when a.state = 'four' then '退回' else '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, b.name as title from system_setup_lowcodebill a left join system_setup_customerform b on a.customer_form_id = b.id INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join system_setup_lowcodebill_current_audit_users m on m.lowcodebill_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where au.id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all 
        SELECT '医德医风考评'   as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'five' then '完结' else '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.title as title from medical_ethics_evaluationofmedicalethics a left join tb_users_message u on u.id = a.apply_user_id left join administrative_company c on a.apply_company_id = c.id left join medical_ethics_evaluationofmedicalethics_current_audit_users m on m.evaluationofmedicalethics_id = a.id left join tb_users_message au on au.id = m.user_id where au.id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all 
        SELECT '会议室申请'   as classification, a.id as id, a.create_time as create_time, a.names as apply_user, a.department as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.real_name as audit_user, a.update_time as audit_time, a.meeting_root as title FROM personal_center_conferenceroomapplication a left join tb_users_message u on a.audit_people_id = u.id where a.audit_people_id = %(audit_user)s and status != '3' GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '大型活动报备'   as classification, a.id as id, a.create_time as create_time, u.real_name as apply_user, c.`name` as company, case when a.state = 'five' then '完结' when a.state = 'four' then '作废' when a.state = 'three' then '退回' else '审核中' END as state, GROUP_CONCAT(DISTINCT au.real_name SEPARATOR ',') as audit_user, a.update_time as audit_time, a.gathering_place as title from administrative_gatheringapply a INNER JOIN tb_users_message u on a.apply_user_id = u.id INNER JOIN administrative_company c on u.company_id = c.id left join administrative_gatheringapply_current_audit_users m on m.gatheringapply_id = a.id LEFT JOIN tb_users_message au on m.user_id = au.id where au.id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '差旅申请' as classification, a.id as id, a.create_time as create_time, a.update_time as apply_user, a.update_time as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_travelapply a left join finance_travelapply_current_audit_users u on a.id = u.travelapply_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state	
        union all
        SELECT '差旅报销' as classification, a.id as id, a.create_time as create_time, a.applicat_id as apply_user, a.applicat_id as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.business_matter as title FROM finance_travelreimbursement a left join finance_travelreimbursement_current_audit_users u on a.id = u.travelreimbursement_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '请假申请' as classification, a.id as id, a.create_time as create_time, a.apply_user_id as apply_user, a.company_id as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.reason as title FROM finance_leaverequest a left join finance_leaverequest_current_audit_users u on a.id = u.leaverequest_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '离职申请' as classification, a.id as id, a.create_time as create_time, a.user_id as apply_user, a.company_id as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, '离职申请' as title FROM finance_dimission a left join finance_dimission_current_audit_users u on a.id = u.dimission_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '合同付款' as classification, a.id as id, a.create_time as create_time, a.apply_user_id as apply_user, a.company_id as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.fund_type as title FROM finance_logisticsoffice a left join finance_logisticsoffice_current_audit_users u on a.id = u.logisticsoffice_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '经济合同会签' as classification, a.id as id, a.create_time as create_time, a.apply_user_id as apply_user, a.company_id as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_businesscontract a left join finance_businesscontract_current_audit_users u on a.id = u.businesscontract_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '固定资产/维修维保付款' as classification, a.id as id, a.create_time as create_time, a.apply_user_id as apply_user, a.apply_user_id as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM personal_center_fixedassets a left join personal_center_fixedassets_current_audit_users u on a.id = u.fixedassets_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '材料付款' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_medicalmaterials a left join finance_medicalmaterials_current_audit_users u on a.id = u.medicalmaterials_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '临床医师单独执业资格' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_solopracticeapply a left join finance_solopracticeapply_current_audit_users u on a.id = u.solopracticeapply_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '手术分级授权' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_surgicalgrading a left join finance_surgicalgrading_current_audit_users u on a.id = u.surgicalgrading_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '新增医疗服务项目' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_newmedicalservices a left join finance_newmedicalservices_current_audit_users u on a.id = u.newmedicalservices_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '一般付款' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_generalfinance a left join finance_generalfinance_current_audit_users u on a.id = u.generalfinance_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '付款流程' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'audit' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM administrative_paymentapproval a LEFT JOIN administrative_paymentapproval_current_audit_users u ON a.id = u.paymentapproval_id WHERE u.user_id = %(audit_user) s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '经济合同会签流程' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'audit' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM administrative_contractapproval a LEFT JOIN administrative_contractapproval_current_audit_users u ON a.id = u.contractapproval_id WHERE u.user_id = %(audit_user) s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '餐补付款' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'audit' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_nutritionalmeals a left join finance_nutritionalmeals_current_audit_users u on a.id = u.nutritionalmeals_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '中层干部' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'seven' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_outgoingcadresdata a left join finance_outgoingcadresdata_current_audit_users u on a.id = u.outgoingcadresdata_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '工会经费' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'seven' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_laborunionexpenses a left join finance_laborunionexpenses_current_audit_users u on a.id = u.laborunionexpenses_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '学科经费' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'seven' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_subjectfunding a left join finance_subjectfunding_current_audit_users u on a.id = u.subjectfunding_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '快速用印授权' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'seven' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_quickauthorization a left join finance_quickauthorization_current_audit_users u on a.id = u.quickauthorization_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '图书/报刊/杂志征订' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'seven' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_booksubscription a left join finance_booksubscription_current_audit_users u on a.id = u.booksubscription_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '党建经费申请' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'seven' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_partybuilding a left join finance_partybuilding_current_audit_users u on a.id = u.partybuilding_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '项目审计送审申请' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'seven' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM finance_objectaudit a left join finance_objectaudit_current_audit_users u on a.id = u.objectaudit_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '服务采购' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'seven' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM logistics_purchasingrequisition a left join logistics_purchasingrequisition_current_audit_users u on a.id = u.purchasingrequisition_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '货物采购' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'seven' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM logistics_goodsprocure a left join logistics_goodsprocure_current_audit_users u on a.id = u.goodsprocure_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '维修改造' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'seven' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM logistics_maintenancerenovation a left join logistics_maintenancerenovation_current_audit_users u on a.id = u.maintenancerenovation_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '项目审计送审申请' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM finance_objectaudit a LEFT JOIN finance_objectaudit_current_audit_users u ON a.id = u.objectaudit_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '计算机及相关设备购置' as classification, a.id as id, a.create_time as create_time, a.create_time as apply_user, a.create_time as company, case when a.state = 'seven' then '完结' else '审核中' END as state, u.id as audit_user, a.update_time as audit_time, a.update_time as title FROM logistics_computerdevice a left join logistics_computerdevice_current_audit_users u on a.id = u.computerdevice_id where u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '招标采购项目' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'seven' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM logistics_biddingprocurementproject a LEFT JOIN logistics_biddingprocurementproject_current_audit_users u ON a.id = u.biddingprocurementproject_id WHERE u.user_id = %(audit_user) s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '招标结果汇报会签' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'seven' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM logistics_tenderingsigning a LEFT JOIN logistics_tenderingsigning_current_audit_users u ON a.id = u.tenderingsigning_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '流程节点修改' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'seven' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM supervision_inspection_flowmodify a LEFT JOIN supervision_inspection_flowmodify_current_audit_users u ON a.id = u.flowmodify_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '短信审批' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'seven' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM supervision_inspection_shortmessageapproval a LEFT JOIN supervision_inspection_shortmessageapproval_current_audit_users u ON a.id = u.shortmessageapproval_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '问责申请' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'seven' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM supervision_inspection_initiateaccountability a LEFT JOIN supervision_inspection_initiateaccountability_current_audit_f16f u ON a.id = u.initiateaccountability_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '委员会议题' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM supervision_inspection_committeetopics a LEFT JOIN supervision_inspection_committeetopics_current_audit_users u ON a.id = u.committeetopics_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '委员会纪要' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM supervision_inspection_committeeminutes a LEFT JOIN supervision_inspection_committeeminutes_current_audit_users u ON a.id = u.committeeminutes_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        union all
        SELECT '调班申请' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'seven' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM supervision_inspection_shiftadjustment a LEFT JOIN supervision_inspection_shiftadjustment_current_audit_users u ON a.id = u.shiftadjustment_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '会议请假' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'seven' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM supervision_inspection_meetingroomleave a LEFT JOIN supervision_inspection_meetingroomleave_current_audit_users u ON a.id = u.meetingroomleave_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '数据外导' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM finance_confidentialdataexport a LEFT JOIN finance_confidentialdataexport_current_audit_users u ON a.id = u.confidentialdataexport_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '公务(外宾)接待事前审批' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM newflowlogic_beforehandreception a LEFT JOIN newflowlogic_beforehandreception_current_audit_users u ON a.id = u.beforehandreception_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '公务(外宾)接待清单审批' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM newflowlogic_receptionchecklist a LEFT JOIN newflowlogic_receptionchecklist_current_audit_users u ON a.id = u.receptionchecklist_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '职工出国(境)审批' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM newflowlogic_employeesabroad a LEFT JOIN newflowlogic_employeesabroad_current_audit_users u ON a.id = u.employeesabroad_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '基建维修改造' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM infrastructure_process_infrastructuremaintenance a LEFT JOIN infrastructure_process_infrastructuremaintenance_current_aud18d7 u ON a.id = u.infrastructuremaintenance_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '工会经济合同会签' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM union_process_economiccountersign a LEFT JOIN union_process_economiccountersign_current_audit_users u ON a.id = u.economiccountersign_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '基建项目专业服务' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM infrastructure_process_professionalservices a LEFT JOIN infrastructure_process_professionalservices_current_audit_users u ON a.id = u.professionalservices_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '工会用印申请' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM union_process_officialseal a LEFT JOIN union_process_officialseal_current_audit_users u ON a.id = u.officialseal_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '工会付款流程' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM union_process_paymentprocess a LEFT JOIN union_process_paymentprocess_current_audit_users u ON a.id = u.paymentprocess_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '工会活动审批' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM union_process_eventapproval a LEFT JOIN union_process_eventapproval_current_audit_users u ON a.id = u.eventapproval_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '工会物资申购' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM union_process_materialsapproval a LEFT JOIN union_process_materialsapproval_current_audit_users u ON a.id = u.materialsapproval_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
        UNION ALL
        SELECT '门诊排班调整' AS classification, a.id AS id, a.create_time AS create_time, a.create_time AS apply_user, a.create_time AS company, CASE WHEN a.state = 'end' THEN '完结' ELSE '审核中' END AS state, u.id AS audit_user, a.update_time AS audit_time, a.update_time AS title FROM union_process_outpatientscheduling a LEFT JOIN union_process_outpatientscheduling_current_audit_users u ON a.id = u.outpatientscheduling_id WHERE u.user_id = %(audit_user)s GROUP BY classification, id, create_time, apply_user, company, state
                ) base
        '''

        sel1 = """SELECT count(id) as num from (SELECT
                (case when a.type = 'a' then '党委会议纪要(收阅)'
                 when a.type = 'b' then '院长办公会会议纪要(收阅)'
                 when a.type = 'c' then '党委专题会议纪要(收阅)'
                 when a.type = 'd' then '院长办公会专题会议纪要(收阅)'
                 when a.type = 'e' then '行政例会简报(收阅)'
                 when a.type = 'f' then '京医发(收阅)'
                 when a.type = 'g' then '党委公文(收阅)'
								 when a.type = 'h' then '京医文(收阅)'
            END) as classification,
                    a.id as id,
                    a.create_time as create_time,
                    u.real_name as apply_user,
                    c.`name` as company,
                    '传阅中' as state,
                    '' as audit_user,
                    a.update_time as audit_time,
                    a.conference_memo_text as title
                FROM administrative_conferencememo a
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join administrative_conferencememopeople m on m.notice_id_id = a.id
                LEFT JOIN tb_users_message au on m.audit_people_id = au.id
                where au.id = %(audit_user)s AND m.state='accept'
                GROUP BY classification, id, create_time, apply_user, company, state

                union all
				
				SELECT
                '上级来文(收阅)' as classification,
                a.id as id,
                a.create_time as create_time,
                u.real_name as apply_user,
                c.`name` as company,
                '传阅中' as state,
                '' as audit_user,
                a.update_time as audit_time,
                a.title as title
                FROM administrative_officialdocuments a
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join administrative_officialdocumentspeople m on m.notice_id_id = a.id
                LEFT JOIN tb_users_message au on m.audit_people_id = au.id
                where au.id = %(audit_user)s AND m.state='accept'
                GROUP BY classification, id, create_time, apply_user, company, state
                union all
				
				SELECT
                '外部来函(收阅)' as classification,
                a.id as id,
                a.create_time as create_time,
                u.real_name as apply_user,
                c.`name` as company,
                '传阅中' as state,
                '' as audit_user,
                a.update_time as audit_time,
                a.title as title
                FROM administrative_correspondence a
                INNER JOIN tb_users_message u on a.apply_user_id = u.id
                INNER JOIN administrative_company c on u.company_id = c.id
                left join administrative_correspondencepeople m on m.notice_id_id = a.id
                LEFT JOIN tb_users_message au on m.audit_people_id = au.id
                where au.id = %(audit_user)s AND m.state='accept'
                GROUP BY classification, id, create_time, apply_user, company, state
                
                union all
                SELECT '委员会纪要' AS classification, a.id AS id, a.create_time AS create_time, u.real_name AS apply_user, c.`name` AS company, '传阅中' AS state, '' AS audit_user, a.update_time AS audit_time, a.conference_memo_text AS title FROM supervision_inspection_committeeminutes a INNER JOIN tb_users_message u ON a.apply_user_id = u.id INNER JOIN administrative_company c ON u.company_id = c.id LEFT JOIN supervision_inspection_committeeminutespeople m ON m.parent_id_id = a.id LEFT JOIN tb_users_message au ON m.audit_people_id = au.id WHERE au.id = %(audit_user)s AND m.state = 'accept' GROUP BY classification, id, create_time, apply_user, company, state
                ) base
								"""

        sql2 = f"""
            SELECT count(id) AS number FROM (
            SELECT A.id FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND B.state='one'
            union all
            SELECT A.id  AS number FROM `supervision_inspection_worksupervisehandle_current_audit_users` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.worksupervisehandle_id=B.id WHERE A.user_id=%(audit_user)s AND (B.state in ('two', 'three', 'four', 'five') or B.old_state in ('two', 'three', 'four', 'five'))
            union all
            SELECT id FROM `supervision_inspection_overdueflow_current_audit_users` WHERE user_id=%(audit_user)s
            union all
            SELECT id FROM `supervision_inspection_deadlinenotification_current_audit_users` WHERE user_id=%(audit_user)s
            union all
            SELECT id FROM `supervision_inspection_departmentperformanceallocation` WHERE assignor_id=%(audit_user)s AND whether_allocate='0'
            union all
            SELECT A.id FROM `supervision_inspection_deadlinenotification` A LEFT JOIN supervision_inspection_worksupervisehandle B ON A.work_id_id=B.id WHERE NOW()>A.end_deadline_time AND A.initiate_or_not='0' AND A.apply_user_id=%(audit_user)s AND B.state IN ('one', 'two')
            ) base
        """

        with connection.cursor() as cursor:
            cursor.execute(sql, {'audit_user': request.user.id, 'audit_user_name': request.user.real_name})
            row = cursor.fetchone()
        # with connection.cursor() as cursor:
            cursor.execute(sel1, {'audit_user': request.user.id, 'audit_user_name': request.user.real_name})
            row1 = cursor.fetchone()

            cursor.execute(sql2, {'audit_user': request.user.id, 'audit_user_name': request.user.real_name})
            row2 = cursor.fetchone()

        make_count = request.user.makecopy_set.filter(look_over="0").count()

        returnDict = {'code': 200, 'message': '操作成功', 'num': row[0] if len(row) else 0, 'num1': row1[0] if len(row1) else 0, "make_count": make_count, "number2": row2[0] if len(row2) else 0}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class UpdateUserInfo(View):
    def get(self, request):
        pw = request.GET.get('pw', None)
        if pw != 'xhhg2022':
            returnDict = {'code': 200, 'message': '该方法为更新操作！请勿调用！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        wb = xlrd.open_workbook(
            "administrative/2022新职工名单.xls")  # 打开文件并返回一个工作蒲对象。open_workbook可以点进去看看函数里面的参数的含义之类的，很详细，英语不好的可以百度翻译，翻译出来的结果差不多。
        sheet_num = wb.nsheets  # 获取excel里面的sheet的数量
        sheet_names = wb.sheet_names()  # 获取到Excel里面所有的sheet的名称列表，即使没有sheet也能用。
        sheet = wb.sheet_by_index(0)  # 通过索引的方式获取到某一个sheet，现在是获取的第一个sheet页，也可以通过sheet的名称进行获取，sheet_by_name('sheet名称')
        rows = sheet.nrows  # 获取sheet页的行数，一共有几行
        columns = sheet.ncols  # 获取sheet页的列数，一共有几列
        # 获取第一行的数据
        row_data = sheet.row_values(3)  # 返回给定的行数的单元格数据进行切片
        # 获取第二列的数据
        col_data = sheet.col_values(1)
        # 获取单元格的数据
        # one_data = sheet.cell(row_index, col_index)  # 同样是通过索引的方式，cell(0,1)获取到的是第一行第二列的单元格数据
        # cell_value = one_data.value  # 获取单元格的值
        # cell_type = one_data.ctype  # 获取单元格的类型，在xlrd中，单元格的数据类型有6种，
        for i in range(3, rows):
            data = sheet.row_values(i)
            job_number = str(int(data[2]))
            real_name = str(data[1])
            department = str(data[3])
            position = "科员"

            user = User.objects.filter(job_number=job_number)
            if len(user) > 0:
                user = user.first()
                user.department = department
                # if position:
                #     user.position = position
                user.save()
            else:
                com = Company.objects.filter(name__contains=department).first()
                User.objects.create_user(
                    username=job_number,
                    password='123456',
                    job_number=job_number,
                    real_name=real_name,
                    department=department,
                    company=com,
                    group_id=6

                )
        returnDict = {'code': 200, 'message': 'ok'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class flow_manage(LoginRequiredMixin, View):
    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        datavalue = request.POST.get("datavalue", None)
        search_val = request.POST.get("search_val", '')
        num1 = (int(page) - 1) * int(page_size)
        num2 = int(page) * int(page_size)
        types = request.POST.get("types", "我的待办")
        flow_name = request.POST.get("flow_name", '')
        if flow_name:
            if flow_name == "1":
                state_list = ['a', 'b', 'c', 'g', 'h']
            elif flow_name == "2":
                state_list = ["d"]
            elif flow_name == "3":
                state_list = ["f"]
            else:
                state_list = ["e"]
            all_count = OfficialDocuments.objects.filter(
                Q(title__contains=search_val) | Q(apply_user__real_name__contains=search_val) | Q(apply_user__department__contains=search_val), audit_users_already=request.user, type__in=state_list).order_by(
                "-create_time").count()
            all_data = OfficialDocuments.objects.filter(
                Q(title__contains=search_val) | Q(apply_user__real_name__contains=search_val) | Q(apply_user__department__contains=search_val), audit_users_already=request.user, type__in=state_list).order_by(
                "-create_time")[num1:num2]
            data_list = [{"title": i.title, "create_by": i.apply_user.real_name, "department": i.apply_user.department,
                          "create_time": i.create_time.strftime("%Y-%m-%d %H:%M"), "id": i.id,
                          "node": i.get_state_str(),
                          "approved": f'<a href="javascript:;" style="color: red;">{", ".join([t.real_name for t in i.current_audit_users.all()])}</a>',
                          "url": f'/personal-center/examinationDetail.html?approve=1&id={i.id}', "admin_add": "",
                          'text': "分发" if i.type == "g" else "修改" if i.type == "f" else "审批", "types": "上级来文"} for i in all_data]
            returnDict = {'status': 'success', "totals": all_count, "data": data_list, "return_data": [], "types": types}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if types == "我的待办":
            data_list, return_data, all_count = SearchData().search_daiban(datavalue, search_val, request, num1, num2)
        elif types == "我的已办":
            data_list, return_data, all_count = SearchData().search_yiban(datavalue, search_val, request, num1, num2)
        else:
            data_list, return_data, all_count = SearchData().search_shenqing(datavalue, search_val, request, num1, num2)
        return_list = []
        if return_data:
            objs = CustomerFormModule.objects.all()
            return_list = {}
            for names in objs:
                return_list[names.name] = {"data": [], "count": 0}

            for i in range(len(return_data)):
                flag = 0
                if i == 0:
                    flag = 1
                if return_data[i][0] in return_list:
                    return_list[return_data[i][0]]["data"].append({"type": return_data[i][1], "number": return_data[i][2], 'flag': flag})
                    return_list[return_data[i][0]]["count"] += int(return_data[i][2])

        returnDict = {'status': 'success', "totals": all_count, "data": data_list, "return_data": return_list, "types": types}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GatheringApplyListView(View):
    def get(self, request):
        user = request.user
        context = {'realname': request.user.real_name, 'position': request.user.post, "table_name": "administrative_gatheringapply"}
        return render(request, 'personal_center/gathering_apply_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = user.gatheringapply_set.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'people_number': obj.people_number, 'apply_user': obj.apply_user.real_name,
                      'company': obj.apply_company.name if obj.apply_company.name else '',
                      'gathering_place': obj.gathering_place,
                      'date': obj.date.strftime("%Y-%m-%d"), 'state': obj.get_state_str(),
                      'url': f"<a href='gathering_apply_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                      if obj.state == 'stop' else f"<a href='gathering_apply_detail_view?id={obj.id}'>查看</a>",
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()])}
                     for
                     obj in
                     objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GatheringApplyView(View):
    def get(self, request):
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, "uuid": uuid.uuid1()}

        return render(request, "personal_center/gathering_apply.html", context)

    def post(self, request):
        user = request.user
        date = request.POST.get('date', None)
        field_leader = request.POST.get('field_leader', None)
        people_number = request.POST.get('people_number', None)
        gathering_note = request.POST.get('gathering_note', None)
        gathering_place = request.POST.get('gathering_place', None)
        uuid = request.POST.get('uuid', None)
        if not all([date, field_leader, people_number, gathering_note, gathering_place, uuid]):
            returnDict = {'code': 500, 'message': '缺少必填参数'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        try:
            com_obj = Company.objects.get(id=80)
            dzb = com_obj.head_people
        except Exception as e:
            returnDict = {'code': 500, 'message': '未找到党政办负责人'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
        obj = GatheringApply.objects.create(apply_user=user, apply_company=user.company, date=date,
                                            field_leader=field_leader, people_number=people_number,
                                            gathering_note=gathering_note, gathering_place=gathering_place, uuid=uuid)
        if not user.company.leaders_id:
            returnDict = {'code': 500, 'message': '该科室未挂分管领导'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if user.company.id != 80:
            obj.current_audit_users.add(user.company.leaders_id)
            GatheringApplyAuditRecord.objects.create(node='B', parent_id=obj, audit_people=user.company.leaders_id, state='unaudit', audit_note='')
        else:
            obj.state = "two"
            obj.current_audit_users.add(dzb)
            obj.save()
        GatheringApplyAuditRecord.objects.create(node='DB', parent_id=obj, audit_people=dzb, state='unaudit', audit_note='')
        GatheringApplyAuditRecord.objects.create(node='yz', parent_id=obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), state='unaudit', audit_note='')
        returnDict = {'code': 200, 'message': '创建成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GatheringApplyDetailView(View):
    def get(self, request):
        id = request.GET.get('id', None)
        obj = GatheringApply.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.gatheringapplyauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.gatheringapplyauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                                   'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        main_file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.uuid, file_type="0")]
        context = {'realname': request.user.real_name, 'position': request.user.post, "flow_dict": flow_dict,
                   'department': request.user.company.name, "obj": obj, "main_file_list": main_file_list,
                   "audit_dic": audit_dic, "file_path": Topicsattachments.objects.filter(topics_number=obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.uuid) else "",
                   "is_audit": "true" if obj.state in ['one', 'two', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if obj.state in ['three'] and request.user == obj.apply_user else 'false',
                   "is_recall": "true" if obj.gatheringapplyauditrecord_set.filter(state__in=['draft', 'audit']).count() == 0 and request.user == obj.apply_user and obj.state not in ('recall', 'stop') else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four'] and request.user == obj.apply_user else 'false',
                   "is_cancel": "true" if obj.state in ['five'] and request.user == obj.apply_user else 'false'
                   }
        return render(request, "personal_center/gathering_apply_detail.html", context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        obj = GatheringApply.objects.get(id=int(id))
        obj.current_audit_users.clear()
        obj.audit_users_already.add(request.user)
        if obj.state == 'one':
            audit_obj = obj.gatheringapplyauditrecord_set.filter(node='B', state='unaudit', audit_people=request.user).first()
            next_audit_record = obj.gatheringapplyauditrecord_set.filter(node='DB', state='unaudit').first()
            if state == 'audit':
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'three'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'two':
            audit_obj = obj.gatheringapplyauditrecord_set.filter(node='DB', state='unaudit', audit_people=request.user).first()
            next_audit_record = obj.gatheringapplyauditrecord_set.filter(node='yz', state='unaudit').first()
            if state == 'audit':
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'three'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'four':
            audit_obj = obj.gatheringapplyauditrecord_set.filter(node='yz', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'five'
            else:
                obj_state = 'three'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.save()
        audit_obj.update_time = datetime.datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class GatheringApplyWriteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        date = request.POST.get('date', None)
        field_leader = request.POST.get('field_leader', None)
        people_number = request.POST.get('people_number', None)
        gathering_note = request.POST.get('gathering_note', None)
        gathering_place = request.POST.get('gathering_place', None)
        obj = GatheringApply.objects.get(id=int(id))
        if date:
            date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
            obj.date = date
        if field_leader:
            obj.field_leader = field_leader
        if people_number:
            obj.people_number = people_number
        if gathering_note:
            obj.gathering_note = gathering_note
        if gathering_place:
            obj.gathering_place = gathering_place
        # obj.current_audit_users
        # for audit_obj in obj.gatheringapplyauditrecord_set.all():
        if obj.gatheringapplyauditrecord_set.filter(node='B', state='unaudit').count() == 0:
            audit_obj = obj.gatheringapplyauditrecord_set.filter(node='B').first()
            GatheringApplyAuditRecord.objects.create(parent_id=obj, node='B', audit_people=audit_obj.audit_people)
        if obj.gatheringapplyauditrecord_set.filter(node='DB', state='unaudit').count() == 0:
            audit_obj = obj.gatheringapplyauditrecord_set.filter(node='DB').first()
            GatheringApplyAuditRecord.objects.create(parent_id=obj, node='DB', audit_people=audit_obj.audit_people)
        obj.current_audit_users.clear()
        b_audit_obj = obj.gatheringapplyauditrecord_set.filter(node='B').first()
        obj.current_audit_users.add(b_audit_obj.audit_people)
        obj.state = 'one'
        obj.save()
        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class GatheringApplyRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = GatheringApply.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'five':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的大型活动申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.gatheringapplyauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的大型活动申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'five':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的大型活动申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


# 议题转会操作
class TransferOperations(View):
    def post(self, request):
        types = request.POST.get('types', None)
        ids = request.POST.get('id', None)
        if types == '1':
            pass
        else:
            obj = Topics.objects.get(id=int(ids))
            TopicsAuditRecord.objects.create(topics_id=obj, audit_people=Staffing.objects.get(station="书记").post_personnel.all().first(), audit_note='', state='unaudit', node='sj')
            now_date = datetime.datetime.now().strftime('%Y-%m-%d')
            topic_meeting_number = Topics.objects.get(id=int(obj.HouseToParty_id)).meetings_num
            TransferOpinions = f"该议题于{now_date.split('-')[0]}年{now_date.split('-')[1]}月{now_date.split('-')[2]}日根据第{topic_meeting_number}次院长办公会提交党委会审议！"
            TopicsAuditRecord.objects.create(topics_id=obj, audit_people=request.user, audit_note=TransferOpinions, state='audit', node='transfer')
            obj.state = 'sj'
            obj.current_audit_user = Staffing.objects.get(station="书记").post_personnel.all().first().real_name
            obj.save()

        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class DeleteDraftView(View):
    def post(self, request):
        id = request.POST.get("id", None)
        table_name = request.POST.get("table_name", None)
        sql_str = f"DELETE FROM {table_name} where id = '{id}'"
        with connection.cursor() as cursor:
            cursor.execute(sql_str)
            connection.commit()
        # for id in id_list:
        # obj = table_name.objects.filter(id=int(id))
        # obj.delete()
        returnData = {'code': 200, 'message': '删除成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class DeleteInBatches(View):
    def post(self, request):
        delete_list = request.POST.get("delete_list", None)
        table_name = request.POST.get("table_name", None)
        id_li = json.loads(delete_list)
        a, b, name_li = 0, 0, []
        for id in id_li:
            if table_name == 'administrative_officialdocuments':
                str_name = 'type'
            else:
                str_name = 'state'
            select_sql = f"SELECT {str_name} FROM {table_name} WHERE id = '{id}'"
            sql_str = f"DELETE FROM {table_name} where id = '{id}'"
            with connection.cursor() as cursor:
                cursor.execute(select_sql)
                row = cursor.fetchone()
                if (row[0] == "draft" or row[0] == "stop") and table_name != "administrative_topics":
                    a += 1
                    cursor.execute(sql_str)
                    connection.commit()
                elif (row[0] == "cg" or row[0] == "stop") and table_name == "administrative_topics":
                    a += 1
                    cursor.execute(sql_str)
                    connection.commit()
                else:
                    b += 1
        if a == 0:
            message = f"未选中流程，{b}个流程无权限删除"
        elif b == 0:
            message = f'成功删除{a}个流程！'
        else:
            message = f"成功删除{a}个流程，{b}个流程无权限删除"
        returnData = {'code': 200, 'message': message}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class UploadMeetingMinutes(View):
    def post(self, request):
        file_id = request.POST.get("file_id", None)
        TopicType = request.POST.get("TopicType", None)
        MeetYear = request.POST.get("MeetYear", None)
        MeetNumber = request.POST.get("MeetNumber", None)

        file_obj = Topicsattachments.objects.get(id=int(file_id))

        topic_obj = topic_meeting.objects.filter(topic_type=TopicType, topic_year=MeetYear, meet_number=MeetNumber)
        for i in range(topic_obj.count()):
            if topic_obj[i].topic.topic_type in ["1", "2", "7"]:
                if i == 0:
                    file_obj.topics_number = topic_obj[i].topic.uuid
                    file_obj.save()
                else:
                    Topicsattachments.objects.create(
                        topics_number=topic_obj[i].topic.uuid,
                        file_path=file_obj.file_path,
                        file_size=file_obj.file_size,
                        uploader=request.user.job_number,
                        file_type='0',
                        is_deleted=file_obj.is_deleted,
                        file_name=file_obj.file_name,
                        pdf_path=file_obj.pdf_path,
                        source='yt',
                        uploader_user=request.user
                    )
        returnData = {'code': 200, 'message': "上传成功！"}
        return HttpResponse(json.dumps(returnData), content_type="application/json")